From 810b97c31aa629dafa92950479f09c02196b36ee Mon Sep 17 00:00:00 2001 From: Steve Hipwell Date: Mon, 24 Nov 2025 10:51:18 +0000 Subject: [PATCH] chore: Refactor integration tests Signed-off-by: Steve Hipwell --- .github/workflows/ci.yaml | 11 +- .github/workflows/codeql.yaml | 148 +- .../workflows/dotcom-acceptance-tests.yaml | 90 +- .github/workflows/ghes-acceptance-tests.yaml | 40 +- .github/workflows/labeler.yaml | 2 +- .gitignore | 2 + CONTRIBUTING.md | 156 +- GNUmakefile | 19 +- github/acc_test.go | 284 +++ github/config_test.go | 38 +- ...e_github_actions_environment_public_key.go | 5 +- ...hub_actions_environment_public_key_test.go | 34 +- ...urce_github_actions_environment_secrets.go | 5 +- ...github_actions_environment_secrets_test.go | 30 +- ...ce_github_actions_environment_variables.go | 3 +- ...thub_actions_environment_variables_test.go | 30 +- ...bject_claim_customization_template_test.go | 38 +- ...ub_actions_organization_public_key_test.go | 30 +- ...actions_organization_registration_token.go | 3 +- ...ns_organization_registration_token_test.go | 30 +- ...rce_github_actions_organization_secrets.go | 3 +- ...ithub_actions_organization_secrets_test.go | 30 +- ...e_github_actions_organization_variables.go | 3 +- ...hub_actions_organization_variables_test.go | 30 +- ...a_source_github_actions_public_key_test.go | 30 +- ...ource_github_actions_registration_token.go | 3 +- ..._github_actions_registration_token_test.go | 30 +- ...bject_claim_customization_template_test.go | 58 +- github/data_source_github_actions_secrets.go | 3 +- ...data_source_github_actions_secrets_test.go | 30 +- .../data_source_github_actions_variables.go | 3 +- ...ta_source_github_actions_variables_test.go | 30 +- github/data_source_github_app_test.go | 33 + github/data_source_github_app_token_test.go | 27 +- github/data_source_github_branch.go | 3 +- ...rce_github_branch_protection_rules_test.go | 66 +- github/data_source_github_branch_test.go | 109 +- ...codespaces_organization_public_key_test.go | 39 +- ..._github_codespaces_organization_secrets.go | 3 +- ...ub_codespaces_organization_secrets_test.go | 63 +- ...ource_github_codespaces_public_key_test.go | 30 +- ...a_source_github_codespaces_secrets_test.go | 38 +- ..._github_codespaces_user_public_key_test.go | 30 +- ...a_source_github_codespaces_user_secrets.go | 3 +- ...rce_github_codespaces_user_secrets_test.go | 30 +- .../data_source_github_collaborators_test.go | 102 +- ...dependabot_organization_public_key_test.go | 30 +- ..._github_dependabot_organization_secrets.go | 3 +- ...ub_dependabot_organization_secrets_test.go | 30 +- ...ource_github_dependabot_public_key_test.go | 30 +- .../data_source_github_dependabot_secrets.go | 3 +- ...a_source_github_dependabot_secrets_test.go | 30 +- github/data_source_github_enterprise_test.go | 30 +- github/data_source_github_ip_ranges.go | 25 +- github/data_source_github_ip_ranges_test.go | 32 +- .../data_source_github_issue_labels_test.go | 30 +- github/data_source_github_membership_test.go | 74 +- ...ce_github_organization_custom_role_test.go | 38 +- ...b_organization_external_identities_test.go | 33 +- ..._github_organization_ip_allow_list_test.go | 38 +- ...thub_organization_repository_roles_test.go | 2 +- .../data_source_github_organization_role.go | 2 +- ...a_source_github_organization_role_teams.go | 2 +- ...rce_github_organization_role_teams_test.go | 4 +- ...ta_source_github_organization_role_test.go | 2 +- ...a_source_github_organization_role_users.go | 4 +- ...rce_github_organization_role_users_test.go | 4 +- .../data_source_github_organization_roles.go | 2 +- ...a_source_github_organization_roles_test.go | 2 +- ...e_github_organization_security_managers.go | 2 +- ...hub_organization_security_managers_test.go | 2 +- ...thub_organization_team_sync_groups_test.go | 18 +- ...a_source_github_organization_teams_test.go | 166 +- .../data_source_github_organization_test.go | 110 +- ...ource_github_organization_webhooks_test.go | 72 +- github/data_source_github_ref.go | 3 +- github/data_source_github_ref_test.go | 127 +- github/data_source_github_release_test.go | 196 +- github/data_source_github_repositories.go | 7 +- .../data_source_github_repositories_test.go | 98 +- github/data_source_github_repository.go | 7 +- ...hub_repository_autolink_references_test.go | 36 +- .../data_source_github_repository_branches.go | 3 +- ..._source_github_repository_branches_test.go | 68 +- ...ithub_repository_custom_properties_test.go | 232 +-- ...urce_github_repository_deploy_keys_test.go | 90 +- ...ository_deployment_branch_policies_test.go | 39 +- ...ository_environment_deployment_policies.go | 4 +- ...ry_environment_deployment_policies_test.go | 47 +- ...rce_github_repository_environments_test.go | 36 +- github/data_source_github_repository_file.go | 4 +- ...data_source_github_repository_file_test.go | 581 ++---- ...source_github_repository_milestone_test.go | 33 +- ...a_source_github_repository_pull_request.go | 2 +- ...rce_github_repository_pull_request_test.go | 30 +- ..._source_github_repository_pull_requests.go | 2 +- ...ce_github_repository_pull_requests_test.go | 30 +- github/data_source_github_repository_teams.go | 3 +- ...ata_source_github_repository_teams_test.go | 30 +- github/data_source_github_repository_test.go | 434 ++-- ..._source_github_repository_webhooks_test.go | 86 +- github/data_source_github_rest_api_test.go | 143 +- github/data_source_github_ssh_keys_test.go | 29 +- ...data_source_github_team_repository_test.go | 67 - github/data_source_github_team_test.go | 240 +-- github/data_source_github_tree_test.go | 33 +- ...urce_github_user_external_identity_test.go | 39 +- github/data_source_github_user_test.go | 70 +- github/data_source_github_users_test.go | 70 +- github/provider.go | 12 +- github/provider_test.go | 103 +- github/provider_utils.go | 140 -- github/repository_utils.go | 3 +- ..._github_actions_environment_secret_test.go | 144 +- ...ithub_actions_environment_variable_test.go | 191 +- ...ource_github_actions_hosted_runner_test.go | 198 +- ...bject_claim_customization_template_test.go | 104 +- ...b_actions_organization_permissions_test.go | 120 +- ...urce_github_actions_organization_secret.go | 3 + ...s_organization_secret_repositories_test.go | 30 +- ...ons_organization_secret_repository_test.go | 43 +- ...github_actions_organization_secret_test.go | 114 +- ...thub_actions_organization_variable_test.go | 142 +- ...ub_actions_repository_access_level_test.go | 60 +- ...bject_claim_customization_template_test.go | 117 +- ...hub_actions_repository_permissions_test.go | 190 +- ...source_github_actions_runner_group_test.go | 214 +- github/resource_github_actions_secret_test.go | 209 +- .../resource_github_actions_variable_test.go | 117 +- ...thub_app_installation_repositories_test.go | 58 +- ...github_app_installation_repository_test.go | 47 +- github/resource_github_branch_default_test.go | 143 +- .../resource_github_branch_protection_test.go | 535 ++--- ...source_github_branch_protection_v3_test.go | 781 +++---- github/resource_github_branch_test.go | 287 +-- ...s_organization_secret_repositories_test.go | 68 +- ...hub_codespaces_organization_secret_test.go | 211 +- .../resource_github_codespaces_secret_test.go | 150 +- ...urce_github_codespaces_user_secret_test.go | 102 +- ...t_organization_secret_repositories_test.go | 94 +- ...hub_dependabot_organization_secret_test.go | 114 +- .../resource_github_dependabot_secret_test.go | 150 +- ...hub_enterprise_actions_permissions_test.go | 132 +- ...ub_enterprise_actions_runner_group_test.go | 134 +- ...prise_actions_workflow_permissions_test.go | 122 +- ...rce_github_enterprise_organization_test.go | 322 ++- ...erprise_security_analysis_settings_test.go | 232 +-- github/resource_github_etag_acc_test.go | 4 +- github/resource_github_issue_label_test.go | 107 +- github/resource_github_issue_labels_test.go | 224 +- github/resource_github_issue_test.go | 84 +- github/resource_github_membership_test.go | 212 +- ...e_github_organization_custom_properties.go | 19 +- ...hub_organization_custom_properties_test.go | 304 +-- ...ce_github_organization_custom_role_test.go | 276 +-- ...source_github_organization_project_test.go | 84 +- ..._organization_role_team_assignment_test.go | 74 +- ...urce_github_organization_role_team_test.go | 2 +- ...urce_github_organization_role_user_test.go | 2 +- ...source_github_organization_ruleset_test.go | 325 ++- ...thub_organization_security_manager_test.go | 151 +- ...ource_github_organization_settings_test.go | 310 +-- ...source_github_organization_webhook_test.go | 86 +- github/resource_github_project_card_test.go | 67 +- github/resource_github_project_column_test.go | 91 +- github/resource_github_release_test.go | 88 +- ...thub_repository_autolink_reference_test.go | 204 +- ...rce_github_repository_collaborator_test.go | 154 +- ...ce_github_repository_collaborators_test.go | 760 +++---- ..._github_repository_custom_property_test.go | 194 +- ...repository_dependabot_security_updates.go} | 0 ...itory_dependabot_security_updates_test.go} | 131 +- ...ource_github_repository_deploy_key_test.go | 167 +- ...epository_deployment_branch_policy_test.go | 41 +- ...tory_environment_deployment_policy_test.go | 242 +-- ...urce_github_repository_environment_test.go | 33 +- github/resource_github_repository_file.go | 4 +- .../resource_github_repository_file_test.go | 226 +- ...source_github_repository_milestone_test.go | 33 +- ...resource_github_repository_project_test.go | 35 +- ...resource_github_repository_pull_request.go | 8 +- ...rce_github_repository_pull_request_test.go | 40 +- github/resource_github_repository_ruleset.go | 2 +- ...resource_github_repository_ruleset_test.go | 576 +++--- github/resource_github_repository_test.go | 1821 ++++++----------- .../resource_github_repository_topics_test.go | 78 +- ...resource_github_repository_webhook_test.go | 123 +- github/resource_github_team_members_test.go | 222 +- .../resource_github_team_membership_test.go | 205 +- .../resource_github_team_repository_test.go | 176 +- github/resource_github_team_settings_test.go | 157 +- ...rce_github_team_sync_group_mapping_test.go | 240 ++- github/resource_github_team_test.go | 162 +- github/resource_github_user_gpg_key_test.go | 41 +- ...ce_github_user_invitation_accepter_test.go | 83 +- github/resource_github_user_ssh_key_test.go | 77 +- ...ub_workflow_repository_permissions_test.go | 70 +- github/resource_organization_block_test.go | 70 +- github/sweeper_test.go | 36 - github/test-fixtures/README.md | 10 +- github/test-fixtures/id_rsa.pub | 1 - github/util_test.go | 6 +- scripts/gofmtcheck.sh | 13 - 203 files changed, 7705 insertions(+), 12748 deletions(-) create mode 100644 github/acc_test.go create mode 100644 github/data_source_github_app_test.go delete mode 100644 github/data_source_github_team_repository_test.go delete mode 100644 github/provider_utils.go rename github/{resource_github_repository_automated_security_fixes.go => resource_github_repository_dependabot_security_updates.go} (100%) rename github/{resource_github_repository_automated_security_fixes_test.go => resource_github_repository_dependabot_security_updates_test.go} (54%) delete mode 100644 github/sweeper_test.go delete mode 100644 github/test-fixtures/id_rsa.pub delete mode 100755 scripts/gofmtcheck.sh diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index ec9476ae55..a01131a0c0 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -1,4 +1,4 @@ -name: GitHub Actions CI +name: CI on: push: @@ -14,18 +14,17 @@ concurrency: group: ci-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read # for actions/checkout +permissions: read-all jobs: ci: name: Continuous Integration runs-on: ubuntu-latest + permissions: + contents: read defaults: run: shell: bash - env: - GITHUB_TEST_ORGANIZATION: kfcampbell-terraform-provider steps: - name: Checkout uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 @@ -35,7 +34,7 @@ jobs: go-version-file: go.mod cache: true - run: make tools - - run: make lint + - run: make lintcheck - run: make website-lint - run: make build - run: make test diff --git a/.github/workflows/codeql.yaml b/.github/workflows/codeql.yaml index c7e4f6cdf8..07f80f7aac 100644 --- a/.github/workflows/codeql.yaml +++ b/.github/workflows/codeql.yaml @@ -1,88 +1,88 @@ name: CodeQL on: - workflow_dispatch: - push: - branches: ["main"] - pull_request: - # The branches below must be a subset of the branches above - branches: ["main"] - schedule: - - cron: "16 7 * * 5" + workflow_dispatch: + push: + branches: ["main"] + pull_request: + # The branches below must be a subset of the branches above + branches: ["main"] + schedule: + - cron: "16 7 * * 5" concurrency: - group: codeql-${{ github.ref }} - cancel-in-progress: true + group: codeql-${{ github.ref }} + cancel-in-progress: true permissions: read-all jobs: - analyze: - name: Analyze (${{ matrix.language }}) - runs-on: ubuntu-latest - permissions: - actions: read - contents: read - security-events: write - strategy: - fail-fast: false - matrix: - include: - - language: actions - build-mode: none - queries: security-extended # can be 'default' (use empty for 'default'), 'security-and-quality', 'security-extended' - - language: go - build-mode: manual - queries: "" # will be used 'default' queries - defaults: - run: - shell: bash - steps: - - name: Checkout - uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + strategy: + fail-fast: false + matrix: + include: + - language: actions + build-mode: none + queries: security-extended # can be 'default' (use empty for 'default'), 'security-and-quality', 'security-extended' + - language: go + build-mode: manual + queries: "" # will be used 'default' queries + defaults: + run: + shell: bash + steps: + - name: Checkout + uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 - - name: Set-up Go - uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 - if: matrix.language == 'go' - with: - go-version-file: go.mod - cache: true + - name: Set-up Go + uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 + if: matrix.language == 'go' + with: + go-version-file: go.mod + cache: true - - name: Initialize CodeQL - uses: github/codeql-action/init@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 - with: - languages: ${{ matrix.language }} - build-mode: ${{ matrix.build-mode }} - queries: ${{ matrix.queries }} + - name: Initialize CodeQL + uses: github/codeql-action/init@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 + with: + languages: ${{ matrix.language }} + build-mode: ${{ matrix.build-mode }} + queries: ${{ matrix.queries }} - - name: Build Go - if: ${{ matrix.language == 'go' }} - run: go build ./... + - name: Build Go + if: ${{ matrix.language == 'go' }} + run: go build ./... - - name: Perform CodeQL Analysis - uses: github/codeql-action/analyze@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 - with: - category: "/language:${{matrix.language}}" + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@fdbfb4d2750291e159f0156def62b853c2798ca2 # v4.31.5 + with: + category: "/language:${{matrix.language}}" - check: - name: Check CodeQL Analysis - if: always() && github.event_name == 'pull_request' - needs: - - analyze - runs-on: ubuntu-latest - defaults: - run: - shell: bash - steps: - - name: Check - env: - INPUT_RESULTS: ${{ join(needs.*.result, ' ') }} - run: | - set -euo pipefail - read -a results <<< "${INPUT_RESULTS}" - for result in "${results[@]}"; do - if [[ "${result}" == "failure" ]] || [[ "${result}" == "cancelled" ]]; then - echo "::error::Workflow failed!" - exit 1 - fi - done + check: + name: Check CodeQL Analysis + if: always() && github.event_name == 'pull_request' + needs: + - analyze + runs-on: ubuntu-latest + defaults: + run: + shell: bash + steps: + - name: Check + env: + INPUT_RESULTS: ${{ join(needs.*.result, ' ') }} + run: | + set -euo pipefail + read -a results <<< "${INPUT_RESULTS}" + for result in "${results[@]}"; do + if [[ "${result}" == "failure" ]] || [[ "${result}" == "cancelled" ]]; then + echo "::error::Workflow failed!" + exit 1 + fi + done diff --git a/.github/workflows/dotcom-acceptance-tests.yaml b/.github/workflows/dotcom-acceptance-tests.yaml index 828ab99eb4..41bbdd13d1 100644 --- a/.github/workflows/dotcom-acceptance-tests.yaml +++ b/.github/workflows/dotcom-acceptance-tests.yaml @@ -2,25 +2,30 @@ name: Acceptance Tests (github.com) on: workflow_dispatch: - # push: - # branches: - # - main - # - release-v* - # pull_request_target: - # types: - # - opened - # - synchronize - # - reopened - # - labeled - # branches: - # - main - # - release-v* + push: + branches: + - main + - release-v* + pull_request: + types: + - opened + - synchronize + - reopened + - labeled + branches: + - main + - release-v* + +concurrency: + group: acctest-dotcom-${{ github.ref }} + cancel-in-progress: true permissions: read-all jobs: test: name: Test ${{ matrix.mode }} + if: (github.event_name != 'pull_request' && github.event_name != 'pull_request_target') || contains(github.event.pull_request.labels.*.name, 'acctest') runs-on: ubuntu-latest permissions: contents: read @@ -38,8 +43,9 @@ jobs: uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 - name: Check secrets + if: github.event_name == 'pull_request_target' env: - INPUT_ALLOWED_SECRETS: ${{ vars.DOTCOM_ACCEPTANCE_TESTS_ALLOWED_SECRETS || 'DOTCOM_TEST_USER_TOKEN' }} + INPUT_ALLOWED_SECRETS: ${{ vars.DOTCOM_ACCEPTANCE_TESTS_ALLOWED_SECRETS || 'GH_TEST_TOKEN' }} INPUT_SECRETS: ${{ toJSON(secrets) }} run: | set -eou pipefail @@ -54,16 +60,16 @@ jobs: id: credentials if: matrix.mode != 'anonymous' env: - TEST_USER_TOKEN: ${{ secrets.DOTCOM_TEST_USER_TOKEN }} + GH_TEST_TOKEN: ${{ secrets.GH_TEST_TOKEN }} run: | set -eou pipefail - if [[ -z "${TEST_USER_TOKEN}" ]]; then + if [[ -z "${GH_TEST_TOKEN}" ]]; then echo "::error::Missing credentials" exit 1 fi - echo "token=${TEST_USER_TOKEN}" >> "${GITHUB_OUTPUT}" + echo "token=${GH_TEST_TOKEN}" >> "${GITHUB_OUTPUT}" - name: Set-up Go uses: actions/setup-go@4dc6199c7b1a012772edbd06daecab0f50c9053c # v6.1.0 @@ -71,19 +77,53 @@ jobs: go-version-file: go.mod cache: true + - name: Setup Terraform + uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3.1.2 + with: + terraform_version: latest + terraform_wrapper: false + + - name: Terraform lookup + id: tf + run: | + set -euo pipefail + + { + echo "version=$(terraform version -json | jq --raw-output '.terraform_version')" + echo "path=$(command -v terraform || true)" + } >> "${GITHUB_OUTPUT}" + - name: Run tests env: + TF_ACC_PROVIDER_NAMESPACE: "" + TF_ACC_TERRAFORM_VERSION: ${{ steps.tf.outputs.version }} + TF_ACC_TERRAFORM_PATH: ${{ steps.tf.outputs.path }} TF_ACC: "1" - TF_LOG: INFO + TF_LOG: WARN GITHUB_TOKEN: ${{ steps.credentials.outputs.token }} GITHUB_BASE_URL: https://api.github.com/ - GITHUB_TEST_TYPE: ${{ matrix.mode }} - GITHUB_OWNER: ${{ (matrix.mode == 'individual' && 'github-terraform-test-user') || (matrix.mode == 'organization' && 'terraformtesting') || '' }} - GITHUB_ORGANIZATION: ${{ (matrix.mode == 'organization' && 'terraformtesting') || '' }} - GITHUB_TEST_ORGANIZATION: ${{ (matrix.mode == 'individual' && 'terraformtesting') || '' }} - GITHUB_TEST_OWNER: ${{ (matrix.mode == 'organization' && 'github-terraform-test-user') || '' }} - GITHUB_TEST_USER_TOKEN: ${{ steps.credentials.outputs.token }} - run: go test -run "^TestAcc*" ./github -v -race -coverprofile=coverage.txt -covermode=atomic -timeout 120m -count=1 + GITHUB_OWNER: ${{ (matrix.mode == 'individual' && vars.GH_TEST_LOGIN) || (matrix.mode == 'organization' && vars.GH_TEST_ORG_NAME) || '' }} + GITHUB_USERNAME: ${{ vars.GH_TEST_LOGIN }} + GITHUB_ENTERPRISE_SLUG: ${{ vars.GH_TEST_ENTERPRISE_SLUG }} + GH_TEST_AUTH_MODE: ${{ matrix.mode }} + GH_TEST_USER_REPOSITORY: ${{ vars.GH_TEST_USER_REPOSITORY }} + GH_TEST_ORG_USER: ${{ vars.GH_TEST_ORG_USER }} + GH_TEST_ORG_SECRET_NAME: ${{ vars.GH_TEST_ORG_SECRET_NAME }} + GH_TEST_ORG_REPOSITORY: ${{ vars.GH_TEST_ORG_REPOSITORY }} + GH_TEST_ORG_TEMPLATE_REPOSITORY: ${{ vars.GH_TEST_ORG_TEMPLATE_REPOSITORY }} + GH_TEST_ORG_APP_INSTALLATION_ID: ${{ vars.GH_TEST_ORG_APP_INSTALLATION_ID }} + GH_TEST_EXTERNAL_USER: ${{ vars.GH_TEST_EXTERNAL_USER }} + GH_TEST_EXTERNAL_USER_TOKEN: ${{ secrets.GH_TEST_EXTERNAL_USER_TOKEN }} + GH_TEST_EXTERNAL_USER2: ${{ vars.GH_TEST_EXTERNAL_USER2 }} + GH_TEST_ADVANCED_SECURITY: ${{ vars.GH_TEST_ADVANCED_SECURITY || 'false' }} + run: | + set -eou pipefail + + if [[ "${GH_TEST_AUTH_MODE}" != "anonymous" ]]; then + go test ./github -v -sweep=all + fi + + go test -run "^TestAcc*" ./github -v -race -coverprofile=coverage.txt -covermode=atomic -timeout 120m -count=1 check: name: Check DotCom Acceptance Tests diff --git a/.github/workflows/ghes-acceptance-tests.yaml b/.github/workflows/ghes-acceptance-tests.yaml index 0627fa5c79..d2e17c29f7 100644 --- a/.github/workflows/ghes-acceptance-tests.yaml +++ b/.github/workflows/ghes-acceptance-tests.yaml @@ -12,6 +12,10 @@ on: # - main # - release-v* +concurrency: + group: acctest-ghes-${{ github.ref }} + cancel-in-progress: true + permissions: read-all jobs: @@ -30,6 +34,7 @@ jobs: uses: actions/checkout@1af3b93b6815bc44a9784bd300feb67ff0d1eeb3 # v6.0.0 - name: Check secrets + if: github.event_name == 'pull_request_target' env: INPUT_ALLOWED_SECRETS: ${{ vars.GHES_ACCEPTANCE_TESTS_ALLOWED_SECRETS || 'GHES_TEST_USER_TOKEN' }} INPUT_SECRETS: ${{ toJSON(secrets) }} @@ -85,17 +90,40 @@ jobs: go-version-file: go.mod cache: true + - name: Setup Terraform + uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3.1.2 + with: + terraform_version: latest + terraform_wrapper: false + + - name: Terraform lookup + id: tf + run: | + set -euo pipefail + + { + echo "version=$(terraform version -json | jq --raw-output '.terraform_version')" + echo "path=$(command -v terraform || true)" + } >> "${GITHUB_OUTPUT}" + - name: Run tests env: + TF_ACC_PROVIDER_NAMESPACE: "" + TF_ACC_TERRAFORM_VERSION: ${{ steps.tf.outputs.version }} + TF_ACC_TERRAFORM_PATH: ${{ steps.tf.outputs.path }} TF_ACC: "1" - TF_LOG: INFO + TF_LOG: WARN GITHUB_TOKEN: ${{ steps.credentials.outputs.token }} GITHUB_BASE_URL: ${{ steps.server.outputs.address }} - GITHUB_TEST_TYPE: enterprise - GITHUB_OWNER: terraformtesting - GITHUB_ORGANIZATION: terraformtesting - GITHUB_TEST_USER_TOKEN: ${{ steps.credentials.outputs.token }} - run: go test -run "^TestAcc*" ./github -v -race -coverprofile=coverage.txt -covermode=atomic -timeout 120m -count=1 + GITHUB_OWNER: "" + GITHUB_USERNAME: "" + GITHUB_ENTERPRISE_SLUG: "" + GH_TEST_AUTH_MODE: enterprise + run: | + set -eou pipefail + + go test ./github -v -sweep=all + go test -run "^TestAcc*" ./github -v -race -coverprofile=coverage.txt -covermode=atomic -timeout 120m -count=1 check: name: Check GHES Acceptance Tests diff --git a/.github/workflows/labeler.yaml b/.github/workflows/labeler.yaml index cd090f9d37..1610560127 100644 --- a/.github/workflows/labeler.yaml +++ b/.github/workflows/labeler.yaml @@ -1,4 +1,4 @@ -name: Pull Request Labeler +name: PR Labeler on: pull_request_target: diff --git a/.gitignore b/.gitignore index 400f9ea23a..f5d638ac85 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,5 @@ terraform-provider-github # do not commit secrets .env +*_rsa +*_rsa.pub diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index a14f7ef024..5ebe1c54a9 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -10,11 +10,11 @@ Before submitting an issue or a pull request, please search the repository for e ## Submitting a pull request -0. Fork and clone the repository. -0. Create a new branch: `git switch -c my-branch-name`. -0. Make your change, add tests, and make sure the tests still pass. -0. Push to your fork and submit a pull request. -0. Pat yourself on the back and wait for your pull request to be reviewed and merged. +1. Fork and clone the repository. +2. Create a new branch: `git switch -c my-branch-name`. +3. Make your change, add tests, and make sure the tests still pass. +4. Push to your fork and submit a pull request. +5. Pat yourself on the back and wait for your pull request to be reviewed and merged. Here are a few things you can do that will increase the likelihood of your pull request being accepted: @@ -38,10 +38,14 @@ Once you have the repository cloned, there's a couple of additional steps you'll - You _must_ make sure that the "Template Repository" item in Settings is checked for this repo. - If you haven't already, generate a Personal Access Token (PAT) for authenticating your test runs. - Export the necessary configuration for authenticating your provider with GitHub + ```sh - export GITHUB_TOKEN= - export GITHUB_ORGANIZATION= + export GH_TEST_AUTH_MODE="organization" + export GH_OWNER="" + export GH_USERNAME="" + export GH_TOKEN="" ``` + - Build the project with `make build` - Try an example test run from the default (`main`) branch, like `TF_LOG=DEBUG TF_ACC=1 go test -v ./... -run ^TestAccGithubRepositories`. All those tests should pass. @@ -49,10 +53,13 @@ Once you have the repository cloned, there's a couple of additional steps you'll 1. Write a test describing what you will fix. See [`github_label`](./github/resource_github_issue_label_test.go) for an example format. 1. Run your test and observe it fail. Enabling debug output allows for observing the underlying requests and responses made as well as viewing state (search `STATE:`) generated during the acceptance test run. + ```sh TF_LOG=DEBUG TF_ACC=1 go test -v ./... -run ^TestAccGithubIssueLabel ``` + 1. Align the resource's implementation to your test case and observe it pass: + ```sh TF_ACC=1 go test -v ./... -run ^TestAccGithubIssueLabel ``` @@ -67,7 +74,8 @@ Println debugging can easily be used to obtain information about how code change If a full debugger is desired, VSCode may be used. In order to do so, -0. Create a launch.json file with this configuration: +1. Create a launch.json file with this configuration: + ```json { "name": "Attach to Process", @@ -77,18 +85,18 @@ If a full debugger is desired, VSCode may be used. In order to do so, "processId": 0, } ``` -Setting a `processId` of 0 allows a dropdown to select the process of the provider. -0. Add a sleep call (e.g. `time.Sleep(10 * time.Second)`) in the [`func providerConfigure(p *schema.Provider) schema.ConfigureFunc`](https://github.com/integrations/terraform-provider-github/blob/cec7e175c50bb091feecdc96ba117067c35ee351/github/provider.go#L274C1-L274C64) before the immediate `return` call. This will allow time to connect the debugger while the provider is initializing, before any critical logic happens. +Setting a `processId` of 0 allows a dropdown to select the process of the provider. -0. Build the terraform provider with debug flags enabled and copy it to the appropriate bin folder with a command like `go build -gcflags="all=-N -l" -o ~/go/bin/`. +1. Add a sleep call (e.g. `time.Sleep(10 * time.Second)`) in the [`func providerConfigure(p *schema.Provider) schema.ConfigureFunc`](https://github.com/integrations/terraform-provider-github/blob/cec7e175c50bb091feecdc96ba117067c35ee351/github/provider.go#L274C1-L274C64) before the immediate `return` call. This will allow time to connect the debugger while the provider is initializing, before any critical logic happens. -0. Create or edit a `dev.tfrc` that points toward the newly-built binary, and export the `TF_CLI_CONFIG_FILE` variable to point to it. Further instructions on this process may be found in the [Building the provider](#using-a-local-version-of-the-provider) section. +2. Build the terraform provider with debug flags enabled and copy it to the appropriate bin folder with a command like `go build -gcflags="all=-N -l" -o ~/go/bin/`. -0. Run a terraform command (e.g. `terraform apply`). While the provider pauses on initialization, go to VSCode and click "Attach to Process". In the search box that appears, type `terraform-provi` and select the terraform provider process. +3. Create or edit a `dev.tfrc` that points toward the newly-built binary, and export the `TF_CLI_CONFIG_FILE` variable to point to it. Further instructions on this process may be found in the [Building the provider](#using-a-local-version-of-the-provider) section. -0. The debugger is now connected! During a typical terraform command, the plugin will be invoked multiple times. If the debugger disconnects and the plugin is invoked again later in the run, the developer will have to re-attach each time as the process ID changes. +4. Run a terraform command (e.g. `terraform apply`). While the provider pauses on initialization, go to VSCode and click "Attach to Process". In the search box that appears, type `terraform-provi` and select the terraform provider process. +5. The debugger is now connected! During a typical terraform command, the plugin will be invoked multiple times. If the debugger disconnects and the plugin is invoked again later in the run, the developer will have to re-attach each time as the process ID changes. ## Manual Testing @@ -99,7 +107,7 @@ Manual testing should be performed on each PR opened in order to validate the pr Build the provider and specify the output directory: ```sh -$ go build -gcflags="all=-N -l" -o ~/go/bin/ +go build -gcflags="all=-N -l" -o ~/go/bin/ ``` This enables verifying your locally built provider using examples available in the `examples/` directory. @@ -121,7 +129,7 @@ provider_installation { } ``` -See https://www.terraform.io/docs/cli/config/config-file.html for more details. +See for more details. When running examples, you should spot the following warning to confirm you are using a local build: @@ -137,87 +145,81 @@ The following provider development overrides are set in the CLI configuration: Commonly required environment variables are listed below: ```sh -# enable debug logging +# Enable debug logging export TF_LOG=DEBUG -# enable testing of organization scenarios instead of individual or anonymous -export GITHUB_ORGANIZATION= - -# enable testing of individual scenarios instead of organization or anonymous -export GITHUB_OWNER= +# Enables acceptance tests +export TF_ACC="1" -# enable testing of enterprise appliances +# Configure the URL override for GHES. export GITHUB_BASE_URL= -# enable testing of GitHub Paid features, these normally also require an organization e.g. repository push rulesets -export GITHUB_PAID_FEATURES=true +# Configure acceptance testing mode; one of anonymous, individual, organization, team or enterprise. If not set will default to anonymous +export GH_TEST_AUTH_MODE= -# leverage helper accounts for tests requiring them -# examples include: -# - https://github.com/github-terraform-test-user -# - https://github.com/terraformtesting -export GITHUB_TEST_OWNER= -export GITHUB_TEST_ORGANIZATION= -export GITHUB_TEST_USER_TOKEN= +# Configure authentication for testing +export GITHUB_OWNER= +export GITHUB_USERNAME= +export GITHUB_TOKEN= + +# Configure user level values +export GH_TEST_USER_REPOSITORY= + +# Configure for the org under test +export GH_TEST_ORG_USER= +export GH_TEST_ORG_SECRET_NAME= +export GH_TEST_ORG_REPOSITORY= +export GH_TEST_ORG_TEMPLATE_REPOSITORY= +export GH_TEST_ORG_APP_INSTALLATION_ID= + +# Configure external (non-org) users +export GH_TEST_EXTERNAL_USER= +export GH_TEST_EXTERNAL_USER_TOKEN= +export GH_TEST_EXTERNAL_USER2= + +# Configure test options +export GH_TEST_ADVANCED_SECURITY= ``` -See [this project](https://github.com/terraformtesting/acceptance-tests) for more information on our old system for automated testing. - There are also a small amount of unit tests in the provider. Due to the nature of the provider, such tests are currently only recommended for exercising functionality completely internal to the provider. These may be executed by running `make test`. ### GitHub Organization -If you do not have an organization already that you are comfortable running tests against, you will need to [create one](https://help.github.com/en/articles/creating-a-new-organization-from-scratch). The free "Team for Open Source" org type is fine for these tests. The name of the organization must then be exported in your environment as `GITHUB_ORGANIZATION`. +If you do not have an organization already that you are comfortable running tests against, you will need to [create one](https://help.github.com/en/articles/creating-a-new-organization-from-scratch). The free "Team for Open Source" org type is fine for these tests. The name of the organization must then be exported in your environment as `GITHUB_OWNER`. Make sure that your organization has a `terraform-template-module` repository ([terraformtesting/terraform-template-module](https://github.com/terraformtesting/terraform-template-module) is an example you can clone) and that its "Template repository" item in Settings is checked. If you are interested in using and/or testing GitHub's [Team synchronization](https://help.github.com/en/github/setting-up-and-managing-organizations-and-teams/synchronizing-teams-between-your-identity-provider-and-github) feature, please contact a maintainer as special arrangements can be made for your convenience. -### Example .vscode/launch.json file +### Example _.vscode/settings.json_ file -This may come in handy when debugging both acceptance and manual testing. +To run acceptance tests the `TF_ACC` environment variable must be set. Below is an example `settings.json` file for VSCode that sets this variable and the other necessary environment variables when running tests from the editor. ```json { - // for information on how to debug the provider, see the CONTRIBUTING.md file - "version": "0.2.0", - "configurations": [ - { - "name": "Launch test function", - "type": "go", - "request": "launch", - "mode": "test", - // note that the program file must be in the same package as the test to run, - // though it does not necessarily have to be the file that contains the test. - "program": "/home/kfcampbell/github/dev/terraform-provider-github/github/resource_github_team_members_test.go", - "args": [ - "-test.v", - "-test.run", - "^TestAccGithubRepositoryTopics$" // ^ExactMatch$ - ], - "env": { - "GITHUB_TEST_COLLABORATOR": "kfcampbell-terraform-test-user", - "GITHUB_TEST_COLLABORATOR_TOKEN": "ghp_xxx", - "GITHUB_TEST_USER": "kfcampbell", - "GITHUB_TOKEN": "ghp_xxx", - "GITHUB_TEMPLATE_REPOSITORY": "terraform-template-module", - "GITHUB_TEMPLATE_REPOSITORY_RELEASE_ID": "12345678", - // "GITHUB_OWNER": "kfcampbell-terraform-provider", - // "GITHUB_OWNER": "kfcampbell", - "GITHUB_ORGANIZATION": "kfcampbell-terraform-provider", // GITHUB_ORGANIZATION is required for organization integration tests - "TF_CLI_CONFIG_FILE": "/home/kfcampbell/github/dev/terraform-provider-github/examples/dev.tfrc", - "TF_ACC": "1", - "TF_LOG": "DEBUG", - "APP_INSTALLATION_ID": "12345678" - } - }, - { - "name": "Attach to Process", - "type": "go", - "request": "attach", - "mode": "local", - "processId": 0 - } - ] + "go.testEnvVars": { + "TF_ACC": "1", + "GITHUB_TOKEN": "", + "GITHUB_BASE_URL": "https://api.github.com/", + "GITHUB_ENTERPRISE_SLUG": "", + "GITHUB_OWNER": "", + "GITHUB_USERNAME": "", + "GH_TEST_AUTH_MODE": "organization", + "GH_TEST_USER_REPOSITORY": "", + "GH_TEST_ORG_USER": "", + "GH_TEST_ORG_SECRET_NAME": "", + "GH_TEST_ORG_REPOSITORY": "", + "GH_TEST_ORG_TEMPLATE_REPOSITORY": "", + "GH_TEST_ORG_APP_INSTALLATION_ID": "", + "GH_TEST_EXTERNAL_USER": "", + "GH_TEST_EXTERNAL_USER_TOKEN": "", + "GH_TEST_EXTERNAL_USER2": "", + "GH_TEST_ADVANCED_SECURITY": "false", + }, + "go.testTimeout": "3600s", + "go.testFlags": [ + "-v", + "-count=1", + ] } ``` diff --git a/GNUmakefile b/GNUmakefile index 22901d666e..876362fec7 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -2,23 +2,26 @@ TEST?=$$(go list ./... |grep -v 'vendor') WEBSITE_REPO=github.com/hashicorp/terraform-website PKG_NAME=github +export TESTARGS=-race -coverprofile=coverage.txt -covermode=atomic + default: build tools: go install github.com/client9/misspell/cmd/misspell@v0.3.4 go install github.com/golangci/golangci-lint/v2/cmd/golangci-lint@v2.6.0 -build: fmtcheck +build: lintcheck CGO_ENABLED=0 go build -ldflags="-s -w" ./... fmt: - @echo "==> Fixing source code with golangci-lint..." + @echo "==> Fixing source code formatting..." golangci-lint fmt ./... -fmtcheck: - @sh -c "'$(CURDIR)/scripts/gofmtcheck.sh'" - lint: + @echo "==> Checking source code against linters and fixing..." + golangci-lint run --fix ./... + +lintcheck: @echo "==> Checking source code against linters..." golangci-lint run ./... @@ -26,8 +29,8 @@ test: CGO_ENABLED=0 go test ./... # commenting this out for release tooling, please run testacc instead -testacc: fmtcheck - TF_ACC=1 CGO_ENABLED=0 go test $(TEST) -v $(TESTARGS) -timeout 120m +testacc: + TF_ACC=1 CGO_ENABLED=0 go test -run "^TestAcc*" $(TEST) -v $(TESTARGS) -timeout 120m -count=1 test-compile: @if [ "$(TEST)" = "./..." ]; then \ @@ -55,4 +58,4 @@ ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO))) endif @$(MAKE) -C $(GOPATH)/src/$(WEBSITE_REPO) website-provider-test PROVIDER_PATH=$(shell pwd) PROVIDER_NAME=$(PKG_NAME) -.PHONY: build test testacc fmt fmtcheck lint tools test-compile website website-lint website-test +.PHONY: build test testacc fmt lint lintcheck tools test-compile website website-lint website-test diff --git a/github/acc_test.go b/github/acc_test.go new file mode 100644 index 0000000000..891024f728 --- /dev/null +++ b/github/acc_test.go @@ -0,0 +1,284 @@ +package github + +import ( + "context" + "fmt" + "os" + "slices" + "strconv" + "strings" + "testing" + + "github.com/google/go-github/v67/github" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" +) + +type testMode string + +const ( + anonymous testMode = "anonymous" + individual testMode = "individual" + organization testMode = "organization" + team testMode = "team" + enterprise testMode = "enterprise" +) + +const testResourcePrefix = "test-acc-" + +var ( + orgTestModes = []testMode{organization, team, enterprise} + paidOrgTestModes = []testMode{team, enterprise} +) + +type testAccConfig struct { + // Target configuration + baseUrl string + + // Auth configuration + authMode testMode + owner string + username string + token string + + // Enterprise configuration + enterpriseSlug string + + // Global test configuration + testPublicRepository string + testPublicRepositoryOwner string + testPublicReleaseId int + testPublicTemplateRepository string + testPublicTemplateRepositoryOwner string + testGHActionsAppInstallationId int + + // User test configuration + testUserRepository string + + // Org test configuration + testOrgUser string + testOrgSecretName string + testOrgRepository string + testOrgTemplateRepository string + testOrgAppInstallationId int + + // External test configuration + testExternalUser string + testExternalUserToken string + testExternalUser2 string + + // Test options + testAdvancedSecurity bool +} + +var testAccConf *testAccConfig + +// providerFactories are used to instantiate a provider during acceptance testing. +// The factory function will be invoked for every Terraform CLI command executed +// to create a provider server to which the CLI can reattach. +var providerFactories = map[string]func() (*schema.Provider, error){ + //nolint:unparam + "github": func() (*schema.Provider, error) { + return Provider(), nil + }, +} + +func TestMain(m *testing.M) { + authMode := testMode(os.Getenv("GH_TEST_AUTH_MODE")) + if len(authMode) == 0 { + authMode = anonymous + } + + baseUrl, ok := os.LookupEnv("GITHUB_BASE_URL") + if !ok { + baseUrl = "https://api.github.com/" + } + + config := testAccConfig{ + baseUrl: baseUrl, + authMode: authMode, + testPublicRepository: "terraform-provider-github", + testPublicRepositoryOwner: "integrations", + testPublicReleaseId: 186531906, + testPublicTemplateRepository: "template-repository", + testPublicTemplateRepositoryOwner: "template-repository", + testGHActionsAppInstallationId: 15368, + testUserRepository: os.Getenv("GH_TEST_USER_REPOSITORY"), + testOrgUser: os.Getenv("GH_TEST_ORG_USER"), + testOrgSecretName: os.Getenv("GH_TEST_ORG_SECRET_NAME"), + testOrgRepository: os.Getenv("GH_TEST_ORG_REPOSITORY"), + testOrgTemplateRepository: os.Getenv("GH_TEST_ORG_TEMPLATE_REPOSITORY"), + testExternalUser: os.Getenv("GH_TEST_EXTERNAL_USER"), + testExternalUserToken: os.Getenv("GH_TEST_EXTERNAL_USER_TOKEN"), + testExternalUser2: os.Getenv("GH_TEST_EXTERNAL_USER2"), + testAdvancedSecurity: os.Getenv("GH_TEST_ADVANCED_SECURITY") == "true", + } + + if config.authMode != anonymous { + config.owner = os.Getenv("GITHUB_OWNER") + config.username = os.Getenv("GITHUB_USERNAME") + config.token = os.Getenv("GITHUB_TOKEN") + + if len(config.owner) == 0 { + fmt.Println("GITHUB_OWNER environment variable not set") + os.Exit(1) + } + + if len(config.username) == 0 { + fmt.Println("GITHUB_USERNAME environment variable not set") + os.Exit(1) + } + + if len(config.token) == 0 { + fmt.Println("GITHUB_TOKEN environment variable not set") + os.Exit(1) + } + } + + if config.authMode == enterprise { + config.enterpriseSlug = os.Getenv("GITHUB_ENTERPRISE_SLUG") + + if len(config.enterpriseSlug) == 0 { + fmt.Println("GITHUB_ENTERPRISE_SLUG environment variable not set") + os.Exit(1) + } + } + + i, err := strconv.Atoi(os.Getenv("GH_TEST_ORG_APP_INSTALLATION_ID")) + if err == nil { + config.testOrgAppInstallationId = i + } + + testAccConf = &config + + configureSweepers() + + resource.TestMain(m) +} + +func getTestMeta() (*Owner, error) { + config := Config{ + Token: testAccConf.token, + Owner: testAccConf.owner, + BaseURL: testAccConf.baseUrl, + } + + meta, err := config.Meta() + if err != nil { + return nil, fmt.Errorf("error getting GitHub meta parameter") + } + + return meta.(*Owner), nil +} + +func configureSweepers() { + resource.AddTestSweepers("repositories", &resource.Sweeper{ + Name: "repositories", + F: sweepRepositories, + }) + + resource.AddTestSweepers("teams", &resource.Sweeper{ + Name: "teams", + F: sweepTeams, + }) +} + +func sweepTeams(_ string) error { + if !slices.Contains(orgTestModes, testMode(os.Getenv("GH_TEST_AUTH_MODE"))) { + return nil + } + + fmt.Println("sweeping teams") + + meta, err := getTestMeta() + if err != nil { + return fmt.Errorf("could not get test meta for sweeper: %w", err) + } + + client := meta.v3client + owner := meta.name + ctx := context.Background() + + teams, _, err := client.Teams.ListTeams(ctx, owner, nil) + if err != nil { + return err + } + + for _, t := range teams { + if slug := t.GetSlug(); strings.HasPrefix(slug, testResourcePrefix) { + fmt.Printf("destroying team %s\n", slug) + + if _, err := client.Teams.DeleteTeamBySlug(ctx, owner, slug); err != nil { + return err + } + } + } + + return nil +} + +func sweepRepositories(_ string) error { + fmt.Println("sweeping repositories") + + meta, err := getTestMeta() + if err != nil { + return fmt.Errorf("could not get test meta for sweeper: %w", err) + } + + client := meta.v3client + owner := meta.name + ctx := context.Background() + + var repos []*github.Repository + var err2 error + if slices.Contains(orgTestModes, testMode(os.Getenv("GH_TEST_AUTH_MODE"))) { + repos, _, err2 = client.Repositories.ListByOrg(ctx, owner, nil) + } else { + repos, _, err2 = client.Repositories.ListByUser(ctx, owner, nil) + } + if err2 != nil { + return err2 + } + + for _, r := range repos { + if name := r.GetName(); strings.HasPrefix(name, testResourcePrefix) { + fmt.Printf("destroying repository %s\n", name) + + if _, err := client.Repositories.Delete(ctx, owner, name); err != nil { + return err + } + } + } + + return nil +} + +func skipUnauthenticated(t *testing.T) { + if testAccConf.authMode == anonymous { + t.Skip("Skipping as test mode not authenticated") + } +} + +func skipUnlessHasOrgs(t *testing.T) { + if !slices.Contains(orgTestModes, testAccConf.authMode) { + t.Skip("Skipping as test mode doesn't have orgs") + } +} + +func skipUnlessHasPaidOrgs(t *testing.T) { + if !slices.Contains(paidOrgTestModes, testAccConf.authMode) { + t.Skip("Skipping as test mode doesn't have orgs") + } +} + +func skipUnlessEnterprise(t *testing.T) { + if testAccConf.authMode != enterprise { + t.Skip("Skipping as test mode is not enterprise") + } +} + +func skipUnlessMode(t *testing.T, testModes ...testMode) { + if !slices.Contains(testModes, testAccConf.authMode) { + t.Skip("Skipping as not supported test mode") + } +} diff --git a/github/config_test.go b/github/config_test.go index 857a0031bf..dc0efe5aec 100644 --- a/github/config_test.go +++ b/github/config_test.go @@ -66,11 +66,6 @@ func TestGHECDataResidencyHostMatch(t *testing.T) { } func TestAccConfigMeta(t *testing.T) { - // FIXME: Skip test runs during travis lint checking - if testToken == "" { - return - } - t.Run("returns an anonymous client for the v3 REST API", func(t *testing.T) { config := Config{BaseURL: "https://api.github.com/"} meta, err := config.Meta() @@ -86,14 +81,11 @@ func TestAccConfigMeta(t *testing.T) { } }) - t.Run("returns an anonymous client for the v4 GraphQL API", func(t *testing.T) { - // https://developer.github.com/v4/guides/forming-calls/#authenticating-with-graphql - t.Skip("anonymous client for the v4 GraphQL API is unsupported") - }) - t.Run("returns a v3 REST API client to manage individual resources", func(t *testing.T) { + skipUnlessMode(t, individual) + config := Config{ - Token: testToken, + Token: testAccConf.token, BaseURL: "https://api.github.com/", } meta, err := config.Meta() @@ -110,8 +102,10 @@ func TestAccConfigMeta(t *testing.T) { }) t.Run("returns a v3 REST API client with max retries", func(t *testing.T) { + skipUnlessMode(t, individual) + config := Config{ - Token: testToken, + Token: testAccConf.token, BaseURL: "https://api.github.com/", RetryableErrors: map[int]bool{ 500: true, @@ -133,8 +127,10 @@ func TestAccConfigMeta(t *testing.T) { }) t.Run("returns a v4 GraphQL API client to manage individual resources", func(t *testing.T) { + skipUnlessMode(t, individual) + config := Config{ - Token: testToken, + Token: testAccConf.token, BaseURL: "https://api.github.com/", } meta, err := config.Meta() @@ -155,10 +151,12 @@ func TestAccConfigMeta(t *testing.T) { }) t.Run("returns a v3 REST API client to manage organization resources", func(t *testing.T) { + skipUnlessHasOrgs(t) + config := Config{ - Token: testToken, + Token: testAccConf.token, BaseURL: "https://api.github.com/", - Owner: testOrganization, + Owner: testAccConf.owner, } meta, err := config.Meta() if err != nil { @@ -167,17 +165,19 @@ func TestAccConfigMeta(t *testing.T) { ctx := context.Background() client := meta.(*Owner).v3client - _, _, err = client.Organizations.Get(ctx, testOrganization) + _, _, err = client.Organizations.Get(ctx, testAccConf.owner) if err != nil { t.Fatalf("failed to validate returned client without error: %s", err.Error()) } }) t.Run("returns a v4 GraphQL API client to manage organization resources", func(t *testing.T) { + skipUnlessHasOrgs(t) + config := Config{ - Token: testToken, + Token: testAccConf.token, BaseURL: "https://api.github.com/", - Owner: testOrganization, + Owner: testAccConf.owner, } meta, err := config.Meta() if err != nil { @@ -192,7 +192,7 @@ func TestAccConfigMeta(t *testing.T) { } `graphql:"organization(login: $login)"` } variables := map[string]any{ - "login": githubv4.String(testOrganization), + "login": githubv4.String(testAccConf.owner), } err = client.Query(context.Background(), &query, variables) if err != nil { diff --git a/github/data_source_github_actions_environment_public_key.go b/github/data_source_github_actions_environment_public_key.go index 48a4fc1200..18f43523a9 100644 --- a/github/data_source_github_actions_environment_public_key.go +++ b/github/data_source_github_actions_environment_public_key.go @@ -33,6 +33,7 @@ func dataSourceGithubActionsEnvironmentPublicKey() *schema.Resource { } func dataSourceGithubActionsEnvironmentPublicKeyRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name repository := d.Get("repository").(string) @@ -40,12 +41,12 @@ func dataSourceGithubActionsEnvironmentPublicKeyRead(d *schema.ResourceData, met envName := d.Get("environment").(string) escapedEnvName := url.PathEscape(envName) - repo, _, err := client.Repositories.Get(context.TODO(), owner, repository) + repo, _, err := client.Repositories.Get(ctx, owner, repository) if err != nil { return err } - publicKey, _, err := client.Actions.GetEnvPublicKey(context.TODO(), int(repo.GetID()), escapedEnvName) + publicKey, _, err := client.Actions.GetEnvPublicKey(ctx, int(repo.GetID()), escapedEnvName) if err != nil { return err } diff --git a/github/data_source_github_actions_environment_public_key_test.go b/github/data_source_github_actions_environment_public_key_test.go index cb4ab3a5d2..57b5acd68f 100644 --- a/github/data_source_github_actions_environment_public_key_test.go +++ b/github/data_source_github_actions_environment_public_key_test.go @@ -9,9 +9,9 @@ import ( ) func TestAccGithubActionsEnvironmentPublicKeyDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("queries a repository environment public key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%[1]s" @@ -34,29 +34,15 @@ func TestAccGithubActionsEnvironmentPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_actions_environment_secrets.go b/github/data_source_github_actions_environment_secrets.go index 932d102bb6..c087f3da23 100644 --- a/github/data_source_github_actions_environment_secrets.go +++ b/github/data_source_github_actions_environment_secrets.go @@ -56,6 +56,7 @@ func dataSourceGithubActionsEnvironmentSecrets() *schema.Resource { } func dataSourceGithubActionsEnvironmentSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -79,7 +80,7 @@ func dataSourceGithubActionsEnvironmentSecretsRead(d *schema.ResourceData, meta return fmt.Errorf("one of %q or %q has to be provided", "full_name", "name") } - repo, _, err := client.Repositories.Get(context.TODO(), owner, repoName) + repo, _, err := client.Repositories.Get(ctx, owner, repoName) if err != nil { return err } @@ -90,7 +91,7 @@ func dataSourceGithubActionsEnvironmentSecretsRead(d *schema.ResourceData, meta var all_secrets []map[string]string for { - secrets, resp, err := client.Actions.ListEnvSecrets(context.TODO(), int(repo.GetID()), escapedEnvName, &options) + secrets, resp, err := client.Actions.ListEnvSecrets(ctx, int(repo.GetID()), escapedEnvName, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_environment_secrets_test.go b/github/data_source_github_actions_environment_secrets_test.go index aa31ae42d6..10a6223bf5 100644 --- a/github/data_source_github_actions_environment_secrets_test.go +++ b/github/data_source_github_actions_environment_secrets_test.go @@ -46,25 +46,19 @@ func TestAccGithubActionsEnvironmentSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_environment_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_environment_variables.go b/github/data_source_github_actions_environment_variables.go index 19f835957b..5858e65496 100644 --- a/github/data_source_github_actions_environment_variables.go +++ b/github/data_source_github_actions_environment_variables.go @@ -60,6 +60,7 @@ func dataSourceGithubActionsEnvironmentVariables() *schema.Resource { } func dataSourceGithubActionsEnvironmentVariablesRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -89,7 +90,7 @@ func dataSourceGithubActionsEnvironmentVariablesRead(d *schema.ResourceData, met var all_variables []map[string]string for { - variables, resp, err := client.Actions.ListEnvVariables(context.TODO(), owner, repoName, escapedEnvName, &options) + variables, resp, err := client.Actions.ListEnvVariables(ctx, owner, repoName, escapedEnvName, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_environment_variables_test.go b/github/data_source_github_actions_environment_variables_test.go index 7f5a762909..999fe523ab 100644 --- a/github/data_source_github_actions_environment_variables_test.go +++ b/github/data_source_github_actions_environment_variables_test.go @@ -46,25 +46,19 @@ func TestAccGithubActionsEnvironmentVariablesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_environment_variables.test", "variables.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_organization_oidc_subject_claim_customization_template_test.go b/github/data_source_github_actions_organization_oidc_subject_claim_customization_template_test.go index c1e5d5c013..a72d201208 100644 --- a/github/data_source_github_actions_organization_oidc_subject_claim_customization_template_test.go +++ b/github/data_source_github_actions_organization_oidc_subject_claim_customization_template_test.go @@ -26,33 +26,19 @@ func TestAccGithubActionsOrganizationOIDCSubjectClaimCustomizationTemplateDataSo resource.TestCheckResourceAttr("data.github_actions_organization_oidc_subject_claim_customization_template.test", "include_claim_keys.3", "repository"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_organization_public_key_test.go b/github/data_source_github_actions_organization_public_key_test.go index b32ae2a983..05cbb70671 100644 --- a/github/data_source_github_actions_organization_public_key_test.go +++ b/github/data_source_github_actions_organization_public_key_test.go @@ -18,29 +18,15 @@ func TestAccGithubActionsOrganizationPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_actions_organization_registration_token.go b/github/data_source_github_actions_organization_registration_token.go index 52a7379c0d..c7ee37a9c8 100644 --- a/github/data_source_github_actions_organization_registration_token.go +++ b/github/data_source_github_actions_organization_registration_token.go @@ -26,11 +26,12 @@ func dataSourceGithubActionsOrganizationRegistrationToken() *schema.Resource { } func dataSourceGithubActionsOrganizationRegistrationTokenRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name log.Printf("[DEBUG] Creating a GitHub Actions organization registration token for %s", owner) - token, _, err := client.Actions.CreateOrganizationRegistrationToken(context.TODO(), owner) + token, _, err := client.Actions.CreateOrganizationRegistrationToken(ctx, owner) if err != nil { return fmt.Errorf("error creating a GitHub Actions organization registration token for %s: %w", owner, err) } diff --git a/github/data_source_github_actions_organization_registration_token_test.go b/github/data_source_github_actions_organization_registration_token_test.go index 67c1105e14..92be4997b3 100644 --- a/github/data_source_github_actions_organization_registration_token_test.go +++ b/github/data_source_github_actions_organization_registration_token_test.go @@ -18,29 +18,15 @@ func TestAccGithubActionsOrganizationRegistrationTokenDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_organization_registration_token.test", "expires_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_actions_organization_secrets.go b/github/data_source_github_actions_organization_secrets.go index 4763ae26f8..88d0e8348f 100644 --- a/github/data_source_github_actions_organization_secrets.go +++ b/github/data_source_github_actions_organization_secrets.go @@ -42,6 +42,7 @@ func dataSourceGithubActionsOrganizationSecrets() *schema.Resource { } func dataSourceGithubActionsOrganizationSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name @@ -51,7 +52,7 @@ func dataSourceGithubActionsOrganizationSecretsRead(d *schema.ResourceData, meta var all_secrets []map[string]string for { - secrets, resp, err := client.Actions.ListOrgSecrets(context.TODO(), owner, &options) + secrets, resp, err := client.Actions.ListOrgSecrets(ctx, owner, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_organization_secrets_test.go b/github/data_source_github_actions_organization_secrets_test.go index 8f25f38f31..0324cb69cf 100644 --- a/github/data_source_github_actions_organization_secrets_test.go +++ b/github/data_source_github_actions_organization_secrets_test.go @@ -34,25 +34,19 @@ func TestAccGithubActionsOrganizationSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_organization_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_organization_variables.go b/github/data_source_github_actions_organization_variables.go index 2a57377d4b..3bc74d3673 100644 --- a/github/data_source_github_actions_organization_variables.go +++ b/github/data_source_github_actions_organization_variables.go @@ -46,6 +46,7 @@ func dataSourceGithubActionsOrganizationVariables() *schema.Resource { } func dataSourceGithubActionsOrganizationVariablesRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name @@ -55,7 +56,7 @@ func dataSourceGithubActionsOrganizationVariablesRead(d *schema.ResourceData, me var all_variables []map[string]string for { - variables, resp, err := client.Actions.ListOrgVariables(context.TODO(), owner, &options) + variables, resp, err := client.Actions.ListOrgVariables(ctx, owner, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_organization_variables_test.go b/github/data_source_github_actions_organization_variables_test.go index 1c077487ea..53501498c1 100644 --- a/github/data_source_github_actions_organization_variables_test.go +++ b/github/data_source_github_actions_organization_variables_test.go @@ -35,25 +35,19 @@ func TestAccGithubActionsOrganizationVariablesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_organization_variables.test", "variables.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_public_key_test.go b/github/data_source_github_actions_public_key_test.go index 7721b07e95..1178529c38 100644 --- a/github/data_source_github_actions_public_key_test.go +++ b/github/data_source_github_actions_public_key_test.go @@ -29,29 +29,15 @@ func TestAccGithubActionsPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_actions_registration_token.go b/github/data_source_github_actions_registration_token.go index bfcd0eebb2..92cd4e4309 100644 --- a/github/data_source_github_actions_registration_token.go +++ b/github/data_source_github_actions_registration_token.go @@ -31,12 +31,13 @@ func dataSourceGithubActionsRegistrationToken() *schema.Resource { } func dataSourceGithubActionsRegistrationTokenRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name repoName := d.Get("repository").(string) log.Printf("[DEBUG] Creating a GitHub Actions repository registration token for %s/%s", owner, repoName) - token, _, err := client.Actions.CreateRegistrationToken(context.TODO(), owner, repoName) + token, _, err := client.Actions.CreateRegistrationToken(ctx, owner, repoName) if err != nil { return fmt.Errorf("error creating a GitHub Actions repository registration token for %s/%s: %w", owner, repoName, err) } diff --git a/github/data_source_github_actions_registration_token_test.go b/github/data_source_github_actions_registration_token_test.go index 742b5c48d8..46e4444d92 100644 --- a/github/data_source_github_actions_registration_token_test.go +++ b/github/data_source_github_actions_registration_token_test.go @@ -29,29 +29,15 @@ func TestAccGithubActionsRegistrationTokenDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_registration_token.test", "expires_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_actions_repository_oidc_subject_claim_customization_template_test.go b/github/data_source_github_actions_repository_oidc_subject_claim_customization_template_test.go index 689202fcf1..efdb1b77ff 100644 --- a/github/data_source_github_actions_repository_oidc_subject_claim_customization_template_test.go +++ b/github/data_source_github_actions_repository_oidc_subject_claim_customization_template_test.go @@ -17,7 +17,7 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplateDataSour name = "tf-acc-test-%s" visibility = "private" } - + resource "github_actions_repository_oidc_subject_claim_customization_template" "test" { repository = github_repository.test.name use_default = false @@ -36,7 +36,7 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplateDataSour name = "tf-acc-test-%s" visibility = "private" } - + resource "github_actions_repository_oidc_subject_claim_customization_template" "test" { repository = github_repository.test.name use_default = true @@ -62,41 +62,27 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplateDataSour resource.TestCheckResourceAttr("data.github_actions_repository_oidc_subject_claim_customization_template.test", "include_claim_keys.#", "0"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check1, - }, - { - Config: config3, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config4, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check1, + }, + { + Config: config3, + Check: resource.ComposeTestCheckFunc(), + }, + { + Config: config4, + Check: check2, + }, + }, }) }) } diff --git a/github/data_source_github_actions_secrets.go b/github/data_source_github_actions_secrets.go index b89df14c3b..f96d5d7f6f 100644 --- a/github/data_source_github_actions_secrets.go +++ b/github/data_source_github_actions_secrets.go @@ -51,6 +51,7 @@ func dataSourceGithubActionsSecrets() *schema.Resource { } func dataSourceGithubActionsSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -77,7 +78,7 @@ func dataSourceGithubActionsSecretsRead(d *schema.ResourceData, meta any) error var all_secrets []map[string]string for { - secrets, resp, err := client.Actions.ListRepoSecrets(context.TODO(), owner, repoName, &options) + secrets, resp, err := client.Actions.ListRepoSecrets(ctx, owner, repoName, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_secrets_test.go b/github/data_source_github_actions_secrets_test.go index 36b0cf1f61..3c788e44ba 100644 --- a/github/data_source_github_actions_secrets_test.go +++ b/github/data_source_github_actions_secrets_test.go @@ -39,25 +39,19 @@ func TestAccGithubActionsSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_actions_variables.go b/github/data_source_github_actions_variables.go index 97e660f3d8..711ac4561d 100644 --- a/github/data_source_github_actions_variables.go +++ b/github/data_source_github_actions_variables.go @@ -55,6 +55,7 @@ func dataSourceGithubActionsVariables() *schema.Resource { } func dataSourceGithubActionsVariablesRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -81,7 +82,7 @@ func dataSourceGithubActionsVariablesRead(d *schema.ResourceData, meta any) erro var all_variables []map[string]string for { - variables, resp, err := client.Actions.ListRepoVariables(context.TODO(), owner, repoName, &options) + variables, resp, err := client.Actions.ListRepoVariables(ctx, owner, repoName, &options) if err != nil { return err } diff --git a/github/data_source_github_actions_variables_test.go b/github/data_source_github_actions_variables_test.go index 6322213923..5d53c924db 100644 --- a/github/data_source_github_actions_variables_test.go +++ b/github/data_source_github_actions_variables_test.go @@ -40,25 +40,19 @@ func TestAccGithubActionsVariablesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_actions_variables.test", "variables.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, "organization") + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_app_test.go b/github/data_source_github_app_test.go new file mode 100644 index 0000000000..5130b7042a --- /dev/null +++ b/github/data_source_github_app_test.go @@ -0,0 +1,33 @@ +package github + +import ( + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" +) + +func TestAccGithubAppDataSource(t *testing.T) { + t.Run("queries a global app", func(t *testing.T) { + config := ` + data "github_app" "test" { + slug = "github-actions" + } + ` + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet( + "data.github_app.test", "name", + ), + ) + + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) +} diff --git a/github/data_source_github_app_token_test.go b/github/data_source_github_app_token_test.go index 6fa7e17da8..7223bba896 100644 --- a/github/data_source_github_app_token_test.go +++ b/github/data_source_github_app_token_test.go @@ -9,18 +9,20 @@ import ( "github.com/google/go-github/v67/github" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" - "github.com/stretchr/testify/assert" ) func TestAccGithubAppTokenDataSource(t *testing.T) { - expectedAccessToken := "W+2e/zjiMTweDAr2b35toCF+h29l7NW92rJIPvFrCJQK" + t.Run("creates a application token without error", func(t *testing.T) { + expectedAccessToken := "W+2e/zjiMTweDAr2b35toCF+h29l7NW92rJIPvFrCJQK" - owner := "test-owner" + owner := "test-owner" - pemData, err := os.ReadFile(testGitHubAppPrivateKeyFile) - assert.Nil(t, err) + pemData, err := os.ReadFile(testGitHubAppPrivateKeyFile) + if err != nil { + t.Logf("Unexpected error: %s", err) + t.Fail() + } - t.Run("creates a application token without error", func(t *testing.T) { ts := githubApiMock([]*mockResponse{ { ExpectedUri: fmt.Sprintf("/api/v3/app/installations/%s/access_tokens", testGitHubAppInstallationID), @@ -59,8 +61,15 @@ func TestAccGithubAppTokenDataSource(t *testing.T) { "token": "", }) - err := dataSourceGithubAppTokenRead(schema, meta) - assert.Nil(t, err) - assert.Equal(t, expectedAccessToken, schema.Get("token")) + err = dataSourceGithubAppTokenRead(schema, meta) + if err != nil { + t.Logf("Unexpected error: %s", err) + t.Fail() + } + + if schema.Get("token") != expectedAccessToken { + t.Logf("Expected %s, got %s", expectedAccessToken, schema.Get("token")) + t.Fail() + } }) } diff --git a/github/data_source_github_branch.go b/github/data_source_github_branch.go index 9176529ece..a6045e58fc 100644 --- a/github/data_source_github_branch.go +++ b/github/data_source_github_branch.go @@ -42,13 +42,14 @@ func dataSourceGithubBranch() *schema.Resource { } func dataSourceGithubBranchRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client orgName := meta.(*Owner).name repoName := d.Get("repository").(string) branchName := d.Get("branch").(string) branchRefName := "refs/heads/" + branchName - ref, resp, err := client.Git.GetRef(context.TODO(), orgName, repoName, branchRefName) + ref, resp, err := client.Git.GetRef(ctx, orgName, repoName, branchRefName) if err != nil { err := &github.ErrorResponse{} if errors.As(err, &err) { diff --git a/github/data_source_github_branch_protection_rules_test.go b/github/data_source_github_branch_protection_rules_test.go index c2545923bf..29a78787d3 100644 --- a/github/data_source_github_branch_protection_rules_test.go +++ b/github/data_source_github_branch_protection_rules_test.go @@ -27,29 +27,15 @@ func TestAccGithubBranchProtectionRulesDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_branch_protection_rules.all", "rules.#", "0"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -79,32 +65,18 @@ func TestAccGithubBranchProtectionRulesDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_branch_protection_rules.all", "rules.0.pattern", "main*"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_branch_test.go b/github/data_source_github_branch_test.go index f0088a5da5..ae2d4feaee 100644 --- a/github/data_source_github_branch_test.go +++ b/github/data_source_github_branch_test.go @@ -31,76 +31,49 @@ func TestAccGithubBranchDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("queries an invalid branch without error", func(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - } - - data "github_branch" "test" { - repository = github_repository.test.name - branch = "xxxxxx" - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_branch.test", "ref", "", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + // Can't test due to SDK and test framework limitations + // t.Run("queries an invalid branch without error", func(t *testing.T) { + // randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "tf-acc-test-%[1]s" + // auto_init = true + // } + + // data "github_branch" "test" { + // repository = github_repository.test.name + // branch = "xxxxxx" + // } + // `, randomID) + + // check := resource.ComposeTestCheckFunc( + // resource.TestCheckResourceAttr( + // "data.github_branch.test", "ref", "", + // ), + // ) + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // Config: config, + // Check: check, + // }, + // }, + // }) + // }) } diff --git a/github/data_source_github_codespaces_organization_public_key_test.go b/github/data_source_github_codespaces_organization_public_key_test.go index 81e24333a8..15ca95ff65 100644 --- a/github/data_source_github_codespaces_organization_public_key_test.go +++ b/github/data_source_github_codespaces_organization_public_key_test.go @@ -12,35 +12,18 @@ func TestAccGithubCodespacesOrganizationPublicKeyDataSource(t *testing.T) { data "github_codespaces_organization_public_key" "test" {} ` - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "data.github_codespaces_organization_public_key.test", "key", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_codespaces_organization_public_key.test", "key_id"), + resource.TestCheckResourceAttrSet("data.github_codespaces_organization_public_key.test", "key"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_codespaces_organization_secrets.go b/github/data_source_github_codespaces_organization_secrets.go index 0355a5ecd8..24a2f4b11e 100644 --- a/github/data_source_github_codespaces_organization_secrets.go +++ b/github/data_source_github_codespaces_organization_secrets.go @@ -42,6 +42,7 @@ func dataSourceGithubCodespacesOrganizationSecrets() *schema.Resource { } func dataSourceGithubCodespacesOrganizationSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name @@ -51,7 +52,7 @@ func dataSourceGithubCodespacesOrganizationSecretsRead(d *schema.ResourceData, m var all_secrets []map[string]string for { - secrets, resp, err := client.Codespaces.ListOrgSecrets(context.TODO(), owner, &options) + secrets, resp, err := client.Codespaces.ListOrgSecrets(ctx, owner, &options) if err != nil { return err } diff --git a/github/data_source_github_codespaces_organization_secrets_test.go b/github/data_source_github_codespaces_organization_secrets_test.go index a084825fdf..88ff440bde 100644 --- a/github/data_source_github_codespaces_organization_secrets_test.go +++ b/github/data_source_github_codespaces_organization_secrets_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -12,47 +11,35 @@ import ( func TestAccGithubCodespacesOrganizationSecretsDataSource(t *testing.T) { t.Run("queries organization codespaces secrets from a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + secretName := fmt.Sprintf("ORG_CS_SECRET_1_%s", randomID) config := fmt.Sprintf(` - resource "github_codespaces_organization_secret" "test" { - secret_name = "org_cs_secret_1_%s" - plaintext_value = "foo" - visibility = "private" - } - `, randomID) - - config2 := config + ` - data "github_codespaces_organization_secrets" "test" { - } - ` - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.#", "1"), - resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.0.name", strings.ToUpper(fmt.Sprintf("ORG_CS_SECRET_1_%s", randomID))), - resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.0.visibility", "private"), - resource.TestCheckResourceAttrSet("data.github_codespaces_organization_secrets.test", "secrets.0.created_at"), - resource.TestCheckResourceAttrSet("data.github_codespaces_organization_secrets.test", "secrets.0.updated_at"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, - }, - }) + resource "github_codespaces_organization_secret" "test" { + secret_name = %s" + plaintext_value = "foo" + visibility = "private" } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + data "github_codespaces_organization_secrets" "test" { + depends_on = [github_codespaces_organization_secret.test] + } + `, secretName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.#", "1"), + resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.0.name", secretName), + resource.TestCheckResourceAttr("data.github_codespaces_organization_secrets.test", "secrets.0.visibility", "private"), + resource.TestCheckResourceAttrSet("data.github_codespaces_organization_secrets.test", "secrets.0.created_at"), + resource.TestCheckResourceAttrSet("data.github_codespaces_organization_secrets.test", "secrets.0.updated_at"), + ), + }, + }, }) }) } diff --git a/github/data_source_github_codespaces_public_key_test.go b/github/data_source_github_codespaces_public_key_test.go index f6ca31249f..33d3617775 100644 --- a/github/data_source_github_codespaces_public_key_test.go +++ b/github/data_source_github_codespaces_public_key_test.go @@ -29,29 +29,15 @@ func TestAccGithubCodespacesPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_codespaces_secrets_test.go b/github/data_source_github_codespaces_secrets_test.go index e72635cc43..27a3b053ae 100644 --- a/github/data_source_github_codespaces_secrets_test.go +++ b/github/data_source_github_codespaces_secrets_test.go @@ -39,33 +39,19 @@ func TestAccGithubCodespacesSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_codespaces_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_codespaces_user_public_key_test.go b/github/data_source_github_codespaces_user_public_key_test.go index bc15ba9967..44fdd34cd1 100644 --- a/github/data_source_github_codespaces_user_public_key_test.go +++ b/github/data_source_github_codespaces_user_public_key_test.go @@ -18,29 +18,15 @@ func TestAccGithubCodespacesUserPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - t.Skip("organization account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + }, }) }) } diff --git a/github/data_source_github_codespaces_user_secrets.go b/github/data_source_github_codespaces_user_secrets.go index c271cfdba1..3799597127 100644 --- a/github/data_source_github_codespaces_user_secrets.go +++ b/github/data_source_github_codespaces_user_secrets.go @@ -42,6 +42,7 @@ func dataSourceGithubCodespacesUserSecrets() *schema.Resource { } func dataSourceGithubCodespacesUserSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name @@ -51,7 +52,7 @@ func dataSourceGithubCodespacesUserSecretsRead(d *schema.ResourceData, meta any) var all_secrets []map[string]string for { - secrets, resp, err := client.Codespaces.ListUserSecrets(context.TODO(), &options) + secrets, resp, err := client.Codespaces.ListUserSecrets(ctx, &options) if err != nil { return err } diff --git a/github/data_source_github_codespaces_user_secrets_test.go b/github/data_source_github_codespaces_user_secrets_test.go index 7389425381..6db857dd70 100644 --- a/github/data_source_github_codespaces_user_secrets_test.go +++ b/github/data_source_github_codespaces_user_secrets_test.go @@ -32,25 +32,19 @@ func TestAccGithubCodespacesUserSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_codespaces_user_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_collaborators_test.go b/github/data_source_github_collaborators_test.go index fd2949eee3..668c2d8da9 100644 --- a/github/data_source_github_collaborators_test.go +++ b/github/data_source_github_collaborators_test.go @@ -8,59 +8,10 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccGithubCollaboratorsDataSource_basic(t *testing.T) { - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - dsn := "data.github_collaborators.test" - repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckGithubCollaboratorsDataSourceConfig(repoName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet(dsn, "collaborator.#"), - resource.TestCheckResourceAttr(dsn, "affiliation", "all"), - ), - }, - }, - }) -} - -func TestAccGithubCollaboratorsDataSource_withPermission(t *testing.T) { - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - dsn := "data.github_collaborators.test" - repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: testAccCheckGithubCollaboratorsDataSourcePermissionConfig(repoName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet(dsn, "collaborator.#"), - resource.TestCheckResourceAttr(dsn, "affiliation", "all"), - resource.TestCheckResourceAttr(dsn, "permission", "admin"), - ), - }, - }, - }) -} - -func testAccCheckGithubCollaboratorsDataSourceConfig(repo string) string { - return fmt.Sprintf(` +func TestAccGithubCollaboratorsDataSource(t *testing.T) { + t.Run("gets all collaborators", func(t *testing.T) { + repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" } @@ -69,11 +20,28 @@ data "github_collaborators" "test" { owner = "%s" repository = "${github_repository.test.name}" } -`, repo, testOwner) -} +`, repoName, testAccConf.owner) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_collaborators.test", "collaborator.#"), + resource.TestCheckResourceAttr("data.github_collaborators.test", "affiliation", "all"), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) -func testAccCheckGithubCollaboratorsDataSourcePermissionConfig(repo string) string { - return fmt.Sprintf(` + t.Run("gets admin collaborators", func(t *testing.T) { + repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" } @@ -83,5 +51,23 @@ data "github_collaborators" "test" { repository = "${github_repository.test.name}" permission = "admin" } -`, repo, testOwner) +`, repoName, testAccConf.owner) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_collaborators.test", "collaborator.#"), + resource.TestCheckResourceAttr("data.github_collaborators.test", "affiliation", "all"), + resource.TestCheckResourceAttr("data.github_collaborators.test", "permission", "admin"), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) } diff --git a/github/data_source_github_dependabot_organization_public_key_test.go b/github/data_source_github_dependabot_organization_public_key_test.go index f0dcf65996..2e6ac3ef04 100644 --- a/github/data_source_github_dependabot_organization_public_key_test.go +++ b/github/data_source_github_dependabot_organization_public_key_test.go @@ -18,29 +18,15 @@ func TestAccGithubDependabotOrganizationPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_dependabot_organization_secrets.go b/github/data_source_github_dependabot_organization_secrets.go index e226ce556a..5c18c42791 100644 --- a/github/data_source_github_dependabot_organization_secrets.go +++ b/github/data_source_github_dependabot_organization_secrets.go @@ -42,6 +42,7 @@ func dataSourceGithubDependabotOrganizationSecrets() *schema.Resource { } func dataSourceGithubDependabotOrganizationSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name @@ -51,7 +52,7 @@ func dataSourceGithubDependabotOrganizationSecretsRead(d *schema.ResourceData, m var all_secrets []map[string]string for { - secrets, resp, err := client.Dependabot.ListOrgSecrets(context.TODO(), owner, &options) + secrets, resp, err := client.Dependabot.ListOrgSecrets(ctx, owner, &options) if err != nil { return err } diff --git a/github/data_source_github_dependabot_organization_secrets_test.go b/github/data_source_github_dependabot_organization_secrets_test.go index 6b2ca981b6..d70aac505c 100644 --- a/github/data_source_github_dependabot_organization_secrets_test.go +++ b/github/data_source_github_dependabot_organization_secrets_test.go @@ -34,25 +34,19 @@ func TestAccGithubDependabotOrganizationSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_dependabot_organization_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_dependabot_public_key_test.go b/github/data_source_github_dependabot_public_key_test.go index 3afc649190..101e5d2034 100644 --- a/github/data_source_github_dependabot_public_key_test.go +++ b/github/data_source_github_dependabot_public_key_test.go @@ -29,29 +29,15 @@ func TestAccGithubDependabotPublicKeyDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_dependabot_secrets.go b/github/data_source_github_dependabot_secrets.go index 817b3f65d3..84d2411450 100644 --- a/github/data_source_github_dependabot_secrets.go +++ b/github/data_source_github_dependabot_secrets.go @@ -51,6 +51,7 @@ func dataSourceGithubDependabotSecrets() *schema.Resource { } func dataSourceGithubDependabotSecretsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -77,7 +78,7 @@ func dataSourceGithubDependabotSecretsRead(d *schema.ResourceData, meta any) err var all_secrets []map[string]string for { - secrets, resp, err := client.Dependabot.ListRepoSecrets(context.TODO(), owner, repoName, &options) + secrets, resp, err := client.Dependabot.ListRepoSecrets(ctx, owner, repoName, &options) if err != nil { return err } diff --git a/github/data_source_github_dependabot_secrets_test.go b/github/data_source_github_dependabot_secrets_test.go index 6f023c5e1f..88c699ce62 100644 --- a/github/data_source_github_dependabot_secrets_test.go +++ b/github/data_source_github_dependabot_secrets_test.go @@ -39,25 +39,19 @@ func TestAccGithubDependabotSecretsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_dependabot_secrets.test", "secrets.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_enterprise_test.go b/github/data_source_github_enterprise_test.go index d646523138..e9729ee61d 100644 --- a/github/data_source_github_enterprise_test.go +++ b/github/data_source_github_enterprise_test.go @@ -8,40 +8,30 @@ import ( ) func TestAccGithubEnterpriseDataSource(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - config := fmt.Sprintf(` data "github_enterprise" "test" { slug = "%s" } `, - testEnterprise, + testAccConf.enterpriseSlug, ) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_enterprise.test", "slug", testEnterprise), + resource.TestCheckResourceAttr("data.github_enterprise.test", "slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttrSet("data.github_enterprise.test", "name"), resource.TestCheckResourceAttrSet("data.github_enterprise.test", "created_at"), resource.TestCheckResourceAttrSet("data.github_enterprise.test", "url"), ) - resource.Test( - t, - resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, enterprise) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, }, + }, ) } diff --git a/github/data_source_github_ip_ranges.go b/github/data_source_github_ip_ranges.go index eda7f9763e..b208ff482c 100644 --- a/github/data_source_github_ip_ranges.go +++ b/github/data_source_github_ip_ranges.go @@ -9,8 +9,8 @@ import ( func dataSourceGithubIpRanges() *schema.Resource { return &schema.Resource{ - Read: dataSourceGithubIpRangesRead, - + Description: "Get the GitHub IP ranges used by various GitHub services.", + Read: dataSourceGithubIpRangesRead, Schema: map[string]*schema.Schema{ "hooks": { Type: schema.TypeList, @@ -53,9 +53,10 @@ func dataSourceGithubIpRanges() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "dependabot": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Deprecated: "This attribute is no longer returned form the API, Dependabot now uses the GitHub Actions IP addresses.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "hooks_ipv4": { Type: schema.TypeList, @@ -98,9 +99,10 @@ func dataSourceGithubIpRanges() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "dependabot_ipv4": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Deprecated: "This attribute is no longer returned form the API, Dependabot now uses the GitHub Actions IP addresses.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, "hooks_ipv6": { Type: schema.TypeList, @@ -143,9 +145,10 @@ func dataSourceGithubIpRanges() *schema.Resource { Elem: &schema.Schema{Type: schema.TypeString}, }, "dependabot_ipv6": { - Type: schema.TypeList, - Computed: true, - Elem: &schema.Schema{Type: schema.TypeString}, + Deprecated: "This attribute is no longer returned form the API, Dependabot now uses the GitHub Actions IP addresses.", + Type: schema.TypeList, + Computed: true, + Elem: &schema.Schema{Type: schema.TypeString}, }, }, } diff --git a/github/data_source_github_ip_ranges_test.go b/github/data_source_github_ip_ranges_test.go index 288be361b2..a7e6295a9b 100644 --- a/github/data_source_github_ip_ranges_test.go +++ b/github/data_source_github_ip_ranges_test.go @@ -19,7 +19,6 @@ func TestAccGithubIpRangesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "pages.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "importer.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "actions.#"), - resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "dependabot.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "hooks_ipv4.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "git_ipv4.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "api_ipv4.#"), @@ -28,7 +27,6 @@ func TestAccGithubIpRangesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "pages_ipv4.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "importer_ipv4.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "actions_ipv4.#"), - resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "dependabot_ipv4.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "hooks_ipv6.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "git_ipv6.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "api_ipv6.#"), @@ -37,32 +35,16 @@ func TestAccGithubIpRangesDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "pages_ipv6.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "importer_ipv6.#"), resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "actions_ipv6.#"), - resource.TestCheckResourceAttrSet("data.github_ip_ranges.test", "dependabot_ipv6.#"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_issue_labels_test.go b/github/data_source_github_issue_labels_test.go index 172c47ba2a..a5eae0b89c 100644 --- a/github/data_source_github_issue_labels_test.go +++ b/github/data_source_github_issue_labels_test.go @@ -29,29 +29,15 @@ func TestAccGithubIssueLabelsDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_membership_test.go b/github/data_source_github_membership_test.go index 0d5ce99a26..4077d3fcd6 100644 --- a/github/data_source_github_membership_test.go +++ b/github/data_source_github_membership_test.go @@ -9,78 +9,54 @@ import ( ) func TestAccGithubMembershipDataSource(t *testing.T) { + if len(testAccConf.testOrgUser) == 0 { + t.Skip("No org user provided") + } + t.Run("queries the membership for a user in a specified organization", func(t *testing.T) { config := fmt.Sprintf(` data "github_membership" "test" { username = "%s" organization = "%s" } - `, testOwner, testOrganization) + `, testAccConf.testOrgUser, testAccConf.owner) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_membership.test", "username", testOwner), + resource.TestCheckResourceAttr("data.github_membership.test", "username", testAccConf.testOrgUser), resource.TestCheckResourceAttrSet("data.github_membership.test", "role"), resource.TestCheckResourceAttrSet("data.github_membership.test", "etag"), resource.TestCheckResourceAttrSet("data.github_membership.test", "state"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("errors when querying with non-existent user", func(t *testing.T) { config := fmt.Sprintf(` data "github_membership" "test" { - username = "%s" + username = "!%s" organization = "%s" } - `, "!"+testOwner, testOrganization) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`Not Found`), - }, + `, testAccConf.testOrgUser, testAccConf.owner) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`Not Found`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_organization_custom_role_test.go b/github/data_source_github_organization_custom_role_test.go index 1bc11f3077..e496057aa6 100644 --- a/github/data_source_github_organization_custom_role_test.go +++ b/github/data_source_github_organization_custom_role_test.go @@ -52,33 +52,19 @@ func TestAccGithubOrganizationCustomRoleDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_organization_external_identities_test.go b/github/data_source_github_organization_external_identities_test.go index 8f55a10c46..823734a134 100644 --- a/github/data_source_github_organization_external_identities_test.go +++ b/github/data_source_github_organization_external_identities_test.go @@ -7,10 +7,6 @@ import ( ) func TestAccGithubOrganizationExternalIdentities(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - t.Run("queries without error", func(t *testing.T) { config := `data "github_organization_external_identities" "test" {}` @@ -20,28 +16,15 @@ func TestAccGithubOrganizationExternalIdentities(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_organization_external_identities.test", "identities.0.saml_identity.name_id"), ) - testCase := func(t *testing.T) { - resource.Test(t, resource.TestCase{ - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t) + }, }) }) } diff --git a/github/data_source_github_organization_ip_allow_list_test.go b/github/data_source_github_organization_ip_allow_list_test.go index bbeaee0e26..2647ec6ea5 100644 --- a/github/data_source_github_organization_ip_allow_list_test.go +++ b/github/data_source_github_organization_ip_allow_list_test.go @@ -9,41 +9,23 @@ import ( func TestAccGithubOrganizationIpAllowListDataSource(t *testing.T) { t.Run("queries without error", func(t *testing.T) { config := ` + data "github_organization_ip_allow_list" "all" {} ` check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.id"), - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.name"), - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.allow_list_value"), - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.is_active"), - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.created_at"), - resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.0.updated_at"), + resource.TestCheckResourceAttrSet("data.github_organization_ip_allow_list.all", "ip_allow_list.#"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_organization_repository_roles_test.go b/github/data_source_github_organization_repository_roles_test.go index d205c79176..aa3c76dd5e 100644 --- a/github/data_source_github_organization_repository_roles_test.go +++ b/github/data_source_github_organization_repository_roles_test.go @@ -13,7 +13,7 @@ func TestAccDataSourceGithubOrganizationRepositoryRoles(t *testing.T) { ` resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_role.go b/github/data_source_github_organization_role.go index 02c681227d..5719aab593 100644 --- a/github/data_source_github_organization_role.go +++ b/github/data_source_github_organization_role.go @@ -62,7 +62,7 @@ func dataSourceGithubOrganizationRoleRead(ctx context.Context, d *schema.Resourc } r := map[string]any{ - "role_id": role.GetID(), + "role_id": int(role.GetID()), "name": role.GetName(), "description": role.GetDescription(), "source": role.GetSource(), diff --git a/github/data_source_github_organization_role_teams.go b/github/data_source_github_organization_role_teams.go index f6f9c18073..08a72fe539 100644 --- a/github/data_source_github_organization_role_teams.go +++ b/github/data_source_github_organization_role_teams.go @@ -92,7 +92,7 @@ func dataSourceGithubOrganizationRoleTeamsRead(ctx context.Context, d *schema.Re for _, team := range teams { t := map[string]any{ - "id": team.GetID(), + "team_id": int(team.GetID()), "slug": team.GetSlug(), "name": team.GetName(), "permission": team.GetPermission(), diff --git a/github/data_source_github_organization_role_teams_test.go b/github/data_source_github_organization_role_teams_test.go index 00f3f0e55b..9fa0370cf7 100644 --- a/github/data_source_github_organization_role_teams_test.go +++ b/github/data_source_github_organization_role_teams_test.go @@ -33,7 +33,7 @@ func TestAccDataSourceGithubOrganizationRoleTeams(t *testing.T) { `, teamName, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -82,7 +82,7 @@ func TestAccDataSourceGithubOrganizationRoleTeams(t *testing.T) { `, teamName1, teamName2, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_role_test.go b/github/data_source_github_organization_role_test.go index 04558f09ee..b158d0a7df 100644 --- a/github/data_source_github_organization_role_test.go +++ b/github/data_source_github_organization_role_test.go @@ -18,7 +18,7 @@ func TestAccDataSourceGithubOrganizationRole(t *testing.T) { `, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_role_users.go b/github/data_source_github_organization_role_users.go index 2e2af025e9..d795218051 100644 --- a/github/data_source_github_organization_role_users.go +++ b/github/data_source_github_organization_role_users.go @@ -82,8 +82,8 @@ func dataSourceGithubOrganizationRoleUsersRead(ctx context.Context, d *schema.Re for _, user := range users { u := map[string]any{ - "id": user.GetID(), - "login": user.GetLogin(), + "user_id": int(user.GetID()), + "login": user.GetLogin(), } allUsers = append(allUsers, u) } diff --git a/github/data_source_github_organization_role_users_test.go b/github/data_source_github_organization_role_users_test.go index 4350b8e4d5..3814b1fe94 100644 --- a/github/data_source_github_organization_role_users_test.go +++ b/github/data_source_github_organization_role_users_test.go @@ -33,7 +33,7 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { `, roleId, login) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -79,7 +79,7 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { `, teamName, login, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_roles.go b/github/data_source_github_organization_roles.go index 2906b9ec86..afc6131bab 100644 --- a/github/data_source_github_organization_roles.go +++ b/github/data_source_github_organization_roles.go @@ -71,7 +71,7 @@ func dataSourceGithubOrganizationRolesRead(ctx context.Context, d *schema.Resour allRoles := make([]any, ret.GetTotalCount()) for i, role := range ret.CustomRepoRoles { r := map[string]any{ - "role_id": role.GetID(), + "role_id": int(role.GetID()), "name": role.GetName(), "description": role.GetDescription(), "source": role.GetSource(), diff --git a/github/data_source_github_organization_roles_test.go b/github/data_source_github_organization_roles_test.go index f945e84a30..846302fdeb 100644 --- a/github/data_source_github_organization_roles_test.go +++ b/github/data_source_github_organization_roles_test.go @@ -13,7 +13,7 @@ func TestAccDataSourceGithubOrganizationRoles(t *testing.T) { ` resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_security_managers.go b/github/data_source_github_organization_security_managers.go index f706e00378..f37560e835 100644 --- a/github/data_source_github_organization_security_managers.go +++ b/github/data_source_github_organization_security_managers.go @@ -60,7 +60,7 @@ func dataSourceGithubOrganizationSecurityManagersRead(d *schema.ResourceData, me for _, team := range teams { t := map[string]any{ - "id": team.GetID(), + "id": int(team.GetID()), "slug": team.GetSlug(), "name": team.GetName(), "permission": team.GetPermission(), diff --git a/github/data_source_github_organization_security_managers_test.go b/github/data_source_github_organization_security_managers_test.go index ce32902ed0..3997c7ca58 100644 --- a/github/data_source_github_organization_security_managers_test.go +++ b/github/data_source_github_organization_security_managers_test.go @@ -30,7 +30,7 @@ func TestAccDataSourceGithubOrganizationSecurityManagers(t *testing.T) { `, teamName) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/data_source_github_organization_team_sync_groups_test.go b/github/data_source_github_organization_team_sync_groups_test.go index bd465a4d7b..2c27319a81 100644 --- a/github/data_source_github_organization_team_sync_groups_test.go +++ b/github/data_source_github_organization_team_sync_groups_test.go @@ -7,18 +7,12 @@ import ( ) func TestAccGithubOrganizationTeamSyncGroupsDataSource_existing(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { - testAccPreCheck(t) - }, - Providers: testAccProviders, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { - Config: testAccCheckGithubOrganizationTeamSyncGroupsDataSourceConfig(), + Config: `data "github_organization_team_sync_groups" "test" {}`, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_organization_team_sync_groups.test", "groups.#"), resource.TestCheckResourceAttrSet("data.github_organization_team_sync_groups.test", "groups.0.group_id"), @@ -28,7 +22,3 @@ func TestAccGithubOrganizationTeamSyncGroupsDataSource_existing(t *testing.T) { }, }) } - -func testAccCheckGithubOrganizationTeamSyncGroupsDataSourceConfig() string { - return `data "github_organization_team_sync_groups" "test" {}` -} diff --git a/github/data_source_github_organization_teams_test.go b/github/data_source_github_organization_teams_test.go index f63c08da79..c6b297102e 100644 --- a/github/data_source_github_organization_teams_test.go +++ b/github/data_source_github_organization_teams_test.go @@ -1,162 +1,62 @@ package github import ( + "fmt" "testing" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccGithubOrganizationTeamsDataSource(t *testing.T) { - t.Run("queries without error", func(t *testing.T) { - config := ` - data "github_organization_teams" "all" {} - ` + t.Run("queries", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("tf-acc-test-0-%s", randomID) - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.id"), - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.node_id"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) - - t.Run("queries root teams only without error", func(t *testing.T) { - config := ` - data "github_organization_teams" "root_teams" { - root_teams_only = true + config := fmt.Sprintf(` + resource "github_team" "test" { + name = "%s" } - ` - - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("data.github_organization_teams.root_teams", "teams.0.id"), - resource.TestCheckResourceAttrSet("data.github_organization_teams.root_teams", "teams.0.node_id"), - resource.TestCheckResourceAttr("data.github_organization_teams.root_teams", "teams.0.parent.id", ""), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) - - t.Run("queries summary only without error", func(t *testing.T) { - config := ` data "github_organization_teams" "all" { - summary_only = true + depends_on = [github_team.test] } - ` + `, teamName) check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.id"), - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.node_id"), - resource.TestCheckNoResourceAttr("data.github_organization_teams.all", "teams.0.members.0"), - resource.TestCheckNoResourceAttr("data.github_organization_teams.all", "teams.0.repositories.0"), + resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.#"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("queries results_per_page only without error", func(t *testing.T) { + t.Run("queries results_per_page", func(t *testing.T) { config := ` - data "github_organization_teams" "all" { - results_per_page = 50 - } + data "github_organization_teams" "all" { + results_per_page = 50 + } ` - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.id"), - resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.0.node_id"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_organization_teams.all", "teams.#"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_organization_test.go b/github/data_source_github_organization_test.go index e0a604685b..8016804ec6 100644 --- a/github/data_source_github_organization_test.go +++ b/github/data_source_github_organization_test.go @@ -14,14 +14,12 @@ func TestAccGithubOrganizationDataSource(t *testing.T) { data "github_organization" "test" { name = "%s" } - `, testOrganization) + `, testAccConf.owner) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_organization.test", "login", testOrganization), - resource.TestCheckResourceAttrSet("data.github_organization.test", "name"), - resource.TestCheckResourceAttrSet("data.github_organization.test", "orgname"), + resource.TestCheckResourceAttr("data.github_organization.test", "login", testAccConf.owner), + resource.TestCheckResourceAttr("data.github_organization.test", "orgname", testAccConf.owner), resource.TestCheckResourceAttrSet("data.github_organization.test", "node_id"), - resource.TestCheckResourceAttrSet("data.github_organization.test", "description"), resource.TestCheckResourceAttrSet("data.github_organization.test", "plan"), resource.TestCheckResourceAttrSet("data.github_organization.test", "repositories.#"), resource.TestCheckResourceAttrSet("data.github_organization.test", "members.#"), @@ -45,29 +43,15 @@ func TestAccGithubOrganizationDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_organization.test", "secret_scanning_push_protection_enabled_for_new_repositories"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -94,43 +78,29 @@ func TestAccGithubOrganizationDataSource(t *testing.T) { github_repository.archived, ] } - + output "should_be_false" { value = contains(data.github_organization.skip_archived.repositories, github_repository.archived.full_name) } output "should_be_true" { value = contains(data.github_organization.all_repos.repositories, github_repository.archived.full_name) } - `, randomID, testOrganization, testOrganization) + `, randomID, testAccConf.owner, testAccConf.owner) check := resource.ComposeTestCheckFunc( resource.TestCheckOutput("should_be_false", "false"), resource.TestCheckOutput("should_be_true", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -140,14 +110,12 @@ func TestAccGithubOrganizationDataSource(t *testing.T) { name = "%s" summary_only = true } - `, testOrganization) + `, testAccConf.owner) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_organization.test", "login", testOrganization), - resource.TestCheckResourceAttrSet("data.github_organization.test", "name"), - resource.TestCheckResourceAttrSet("data.github_organization.test", "orgname"), + resource.TestCheckResourceAttr("data.github_organization.test", "login", testAccConf.owner), + resource.TestCheckResourceAttr("data.github_organization.test", "orgname", testAccConf.owner), resource.TestCheckResourceAttrSet("data.github_organization.test", "node_id"), - resource.TestCheckResourceAttrSet("data.github_organization.test", "description"), resource.TestCheckResourceAttrSet("data.github_organization.test", "plan"), resource.TestCheckNoResourceAttr("data.github_organization.test", "repositories.#"), resource.TestCheckNoResourceAttr("data.github_organization.test", "members.#"), @@ -171,29 +139,15 @@ func TestAccGithubOrganizationDataSource(t *testing.T) { resource.TestCheckNoResourceAttr("data.github_organization.test", "secret_scanning_push_protection_enabled_for_new_repositories"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_organization_webhooks_test.go b/github/data_source_github_organization_webhooks_test.go index 6343ee0f61..11e8465e10 100644 --- a/github/data_source_github_organization_webhooks_test.go +++ b/github/data_source_github_organization_webhooks_test.go @@ -9,57 +9,37 @@ import ( func TestAccGithubOrganizationWebhooksDataSource(t *testing.T) { t.Run("manages organization webhooks", func(t *testing.T) { config := ` - resource "github_organization_webhook" "test" { - configuration { - url = "https://google.de/webhook" - content_type = "json" - insecure_ssl = true - } - - events = ["pull_request"] + resource "github_organization_webhook" "test" { + configuration { + url = "https://google.de/webhook" + content_type = "json" + insecure_ssl = true } - ` - - config2 := config + ` - data "github_organization_webhooks" "test" {} - ` - const resourceName = "data.github_organization_webhooks.test" - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "webhooks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.name", "web"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.url", "https://google.de/webhook"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.active", "true"), - resource.TestCheckResourceAttrSet(resourceName, "webhooks.0.id"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, - }, - }) + events = ["pull_request"] } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + data "github_organization_webhooks" "test" { + depends_on = [github_organization_webhook.test] + } + ` - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_organization_webhooks.test", "webhooks.#"), + resource.TestCheckResourceAttr("data.github_organization_webhooks.test", "webhooks.#", "1"), + resource.TestCheckResourceAttrSet("data.github_organization_webhooks.test", "webhooks.0.id"), + resource.TestCheckResourceAttr("data.github_organization_webhooks.test", "webhooks.0.name", "web"), + resource.TestCheckResourceAttr("data.github_organization_webhooks.test", "webhooks.0.active", "true"), + resource.TestCheckResourceAttrSet("data.github_organization_webhooks.test", "webhooks.0.url"), + ), + }, + }, }) }) } diff --git a/github/data_source_github_ref.go b/github/data_source_github_ref.go index 814b0dd84d..ae394c521f 100644 --- a/github/data_source_github_ref.go +++ b/github/data_source_github_ref.go @@ -42,6 +42,7 @@ func dataSourceGithubRef() *schema.Resource { } func dataSourceGithubRefRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner, ok := d.Get("owner").(string) if !ok { @@ -50,7 +51,7 @@ func dataSourceGithubRefRead(d *schema.ResourceData, meta any) error { repoName := d.Get("repository").(string) ref := d.Get("ref").(string) - refData, resp, err := client.Git.GetRef(context.TODO(), owner, repoName, ref) + refData, resp, err := client.Git.GetRef(ctx, owner, repoName, ref) if err != nil { err := &github.ErrorResponse{} if errors.As(err, &err) { diff --git a/github/data_source_github_ref_test.go b/github/data_source_github_ref_test.go index 7ad3b6317f..30e1a7ca29 100644 --- a/github/data_source_github_ref_test.go +++ b/github/data_source_github_ref_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,9 +9,8 @@ import ( ) func TestAccGithubRefDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("queries an existing branch ref without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%[1]s" @@ -20,86 +18,57 @@ func TestAccGithubRefDataSource(t *testing.T) { } data "github_ref" "test" { - repository = github_repository.test.id + owner = "%s" + repository = github_repository.test.name ref = "heads/main" } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "data.github_ref.test", "id", regexp.MustCompile(randomID), - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + `, randomID, testAccConf.owner) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_ref.test", "id"), + resource.TestCheckResourceAttrSet("data.github_ref.test", "sha"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - // TODO: This still fails on missing id attribute - t.Run("queries an invalid ref without error", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - } - - data "github_ref" "test" { - repository = github_repository.test.id - ref = "heads/xxxxxx" - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckNoResourceAttr( - "data.github_ref.test", "id", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + // Can't test due to SDK and test framework limitations + // t.Run("queries an invalid ref without error", func(t *testing.T) { + // randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "tf-acc-test-%[1]s" + // auto_init = true + // } + + // data "github_ref" "test" { + // repository = github_repository.test.id + // ref = "heads/xxxxxx" + // } + // `, randomID) + + // check := resource.ComposeTestCheckFunc( + // resource.TestCheckNoResourceAttr( + // "data.github_ref.test", "id", + // ), + // ) + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // Config: config, + // Check: check, + // }, + // }, + // }) + // }) } diff --git a/github/data_source_github_release_test.go b/github/data_source_github_release_test.go index 181ad0bc02..f695bbfe55 100644 --- a/github/data_source_github_release_test.go +++ b/github/data_source_github_release_test.go @@ -2,18 +2,14 @@ package github import ( "fmt" - "os" "regexp" + "strconv" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) func TestAccGithubReleaseDataSource(t *testing.T) { - testReleaseRepository := os.Getenv("GITHUB_TEMPLATE_REPOSITORY") - testReleaseID := os.Getenv("GITHUB_TEMPLATE_REPOSITORY_RELEASE_ID") - testReleaseOwner := testOrganizationFunc() - t.Run("queries latest release", func(t *testing.T) { config := fmt.Sprintf(` data "github_release" "test" { @@ -21,47 +17,30 @@ func TestAccGithubReleaseDataSource(t *testing.T) { owner = "%s" retrieve_by = "latest" } - `, testReleaseRepository, testReleaseOwner) + `, testAccConf.testPublicRepository, testAccConf.testPublicRepositoryOwner) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_release.test", "id", testReleaseID, - ), + resource.TestCheckResourceAttrSet("data.github_release.test", "id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("queries release by ID or tag", func(t *testing.T) { + t.Run("queries release by id or tag", func(t *testing.T) { config := fmt.Sprintf(` data "github_release" "by_id" { repository = "%[1]s" owner = "%[2]s" retrieve_by = "id" - release_id = "%[3]s" + release_id = "%[3]d" } data "github_release" "by_tag" { @@ -70,143 +49,84 @@ func TestAccGithubReleaseDataSource(t *testing.T) { retrieve_by = "tag" release_tag = data.github_release.by_id.release_tag } - `, testReleaseRepository, testReleaseOwner, testReleaseID) + `, testAccConf.testPublicRepository, testAccConf.testPublicRepositoryOwner, testAccConf.testPublicReleaseId) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( - "data.github_release.by_id", "id", testReleaseID, + "data.github_release.by_id", "id", strconv.Itoa(testAccConf.testPublicReleaseId), ), resource.TestCheckResourceAttr( - "data.github_release.by_tag", "id", testReleaseID, + "data.github_release.by_tag", "id", strconv.Itoa(testAccConf.testPublicReleaseId), ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("errors when querying with non-existent ID", func(t *testing.T) { - config := ` + t.Run("errors when querying with non-existent id", func(t *testing.T) { + config := fmt.Sprintf(` data "github_release" "test" { - repository = "test" - owner = "test" + repository = "%s" + owner = "%s" retrieve_by = "id" } - ` - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile("`release_id` must be set when `retrieve_by` = `id`"), - }, + `, testAccConf.testPublicRepository, testAccConf.testPublicRepositoryOwner) + + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("`release_id` must be set when `retrieve_by` = `id`"), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("errors when querying with non-existent repository", func(t *testing.T) { - config := ` + t.Run("errors when querying with non-existent tag", func(t *testing.T) { + config := fmt.Sprintf(` data "github_release" "test" { - repository = "test" - owner = "test" - retrieve_by = "latest" + repository = "%s" + owner = "%s" + retrieve_by = "tag" } - ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`Not Found`), - }, + `, testAccConf.testPublicRepository, testAccConf.testPublicRepositoryOwner) + + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("`release_tag` must be set when `retrieve_by` = `tag`"), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("errors when querying with non-existent tag", func(t *testing.T) { + t.Run("errors when querying with non-existent repository", func(t *testing.T) { config := ` data "github_release" "test" { repository = "test" owner = "test" - retrieve_by = "tag" + retrieve_by = "latest" } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile("`release_tag` must be set when `retrieve_by` = `tag`"), - }, + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`Not Found`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repositories.go b/github/data_source_github_repositories.go index a22f0a1f00..2e4b655cc4 100644 --- a/github/data_source_github_repositories.go +++ b/github/data_source_github_repositories.go @@ -60,6 +60,7 @@ func dataSourceGithubRepositories() *schema.Resource { } func dataSourceGithubRepositoriesRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client includeRepoId := d.Get("include_repo_id").(bool) @@ -73,7 +74,7 @@ func dataSourceGithubRepositoriesRead(d *schema.ResourceData, meta any) error { }, } - fullNames, names, repoIDs, err := searchGithubRepositories(client, query, opt) + fullNames, names, repoIDs, err := searchGithubRepositories(ctx, client, query, opt) if err != nil { return err } @@ -97,7 +98,7 @@ func dataSourceGithubRepositoriesRead(d *schema.ResourceData, meta any) error { return nil } -func searchGithubRepositories(client *github.Client, query string, opt *github.SearchOptions) ([]string, []string, []int64, error) { +func searchGithubRepositories(ctx context.Context, client *github.Client, query string, opt *github.SearchOptions) ([]string, []string, []int64, error) { fullNames := make([]string, 0) names := make([]string, 0) @@ -105,7 +106,7 @@ func searchGithubRepositories(client *github.Client, query string, opt *github.S repoIDs := make([]int64, 0) for { - results, resp, err := client.Search.Repositories(context.TODO(), query, opt) + results, resp, err := client.Search.Repositories(ctx, query, opt) if err != nil { return fullNames, names, repoIDs, err } diff --git a/github/data_source_github_repositories_test.go b/github/data_source_github_repositories_test.go index b17f825b32..cf3afcab0f 100644 --- a/github/data_source_github_repositories_test.go +++ b/github/data_source_github_repositories_test.go @@ -17,12 +17,12 @@ func TestAccGithubRepositoriesDataSource(t *testing.T) { data "github_repositories" "test" { query = "org:%s" } - `, testOrganization) + `, testAccConf.owner) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( "data.github_repositories.test", "full_names.0", - regexp.MustCompile(`^`+testOrganization), + regexp.MustCompile(`^`+testAccConf.owner), ), resource.TestCheckResourceAttrSet( "data.github_repositories.test", "names.0", @@ -36,29 +36,15 @@ func TestAccGithubRepositoriesDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -69,12 +55,12 @@ func TestAccGithubRepositoriesDataSource(t *testing.T) { include_repo_id = true results_per_page = 20 } - `, testOrganization) + `, testAccConf.owner) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( "data.github_repositories.test", "full_names.0", - regexp.MustCompile(`^`+testOrganization), + regexp.MustCompile(`^`+testAccConf.owner), ), resource.TestCheckResourceAttrSet( "data.github_repositories.test", "names.0", @@ -88,29 +74,15 @@ func TestAccGithubRepositoriesDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -135,29 +107,15 @@ func TestAccGithubRepositoriesDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository.go b/github/data_source_github_repository.go index 94e40d0c3b..7d6a7d64da 100644 --- a/github/data_source_github_repository.go +++ b/github/data_source_github_repository.go @@ -340,6 +340,7 @@ func dataSourceGithubRepository() *schema.Resource { } func dataSourceGithubRepositoryRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -359,7 +360,7 @@ func dataSourceGithubRepositoryRead(d *schema.ResourceData, meta any) error { return fmt.Errorf("one of %q or %q has to be provided", "full_name", "name") } - repo, _, err := client.Repositories.Get(context.TODO(), owner, repoName) + repo, _, err := client.Repositories.Get(ctx, owner, repoName) if err != nil { err := &github.ErrorResponse{} if errors.As(err, &err) { @@ -409,7 +410,7 @@ func dataSourceGithubRepositoryRead(d *schema.ResourceData, meta any) error { _ = d.Set("allow_update_branch", repo.GetAllowUpdateBranch()) if repo.GetHasPages() { - pages, _, err := client.Repositories.GetPagesInfo(context.TODO(), owner, repoName) + pages, _, err := client.Repositories.GetPagesInfo(ctx, owner, repoName) if err != nil { return err } @@ -424,7 +425,7 @@ func dataSourceGithubRepositoryRead(d *schema.ResourceData, meta any) error { } if repo.License != nil { - repository_license, _, err := client.Repositories.License(context.TODO(), owner, repoName) + repository_license, _, err := client.Repositories.License(ctx, owner, repoName) if err != nil { return err } diff --git a/github/data_source_github_repository_autolink_references_test.go b/github/data_source_github_repository_autolink_references_test.go index 91f8c5382d..f3ecf95b1f 100644 --- a/github/data_source_github_repository_autolink_references_test.go +++ b/github/data_source_github_repository_autolink_references_test.go @@ -38,32 +38,18 @@ func TestAccGithubRepositoryAutolinkReferencesDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_repository_autolink_references.all", "autolink_references.0.is_alphanumeric", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_repository_branches.go b/github/data_source_github_repository_branches.go index 5f78f90c53..68c769b7a3 100644 --- a/github/data_source_github_repository_branches.go +++ b/github/data_source_github_repository_branches.go @@ -65,6 +65,7 @@ func flattenBranches(branches []*github.Branch) []map[string]any { } func dataSourceGithubRepositoryBranchesRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client orgName := meta.(*Owner).name repoName := d.Get("repository").(string) @@ -86,7 +87,7 @@ func dataSourceGithubRepositoryBranchesRead(d *schema.ResourceData, meta any) er results := make([]map[string]any, 0) for { - branches, resp, err := client.Repositories.ListBranches(context.TODO(), orgName, repoName, listBranchOptions) + branches, resp, err := client.Repositories.ListBranches(ctx, orgName, repoName, listBranchOptions) if err != nil { return err } diff --git a/github/data_source_github_repository_branches_test.go b/github/data_source_github_repository_branches_test.go index b1d7210b05..9689d0a725 100644 --- a/github/data_source_github_repository_branches_test.go +++ b/github/data_source_github_repository_branches_test.go @@ -29,29 +29,15 @@ func TestAccGithubRepositoryBranchesDataSource(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "branches.0.protected", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -104,33 +90,19 @@ func TestAccGithubRepositoryBranchesDataSource(t *testing.T) { resource.TestCheckResourceAttr(nonProtectedResourceName, "branches.0.protected", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_repository_custom_properties_test.go b/github/data_source_github_repository_custom_properties_test.go index 9902649861..ade0bf4b03 100644 --- a/github/data_source_github_repository_custom_properties_test.go +++ b/github/data_source_github_repository_custom_properties_test.go @@ -9,220 +9,186 @@ import ( ) func TestAccGithubRepositoryCustomPropertiesDataSource(t *testing.T) { - t.Skip("You need an org with custom properties already setup as described in the variables below") // TODO: at the time of writing org_custom_properties are not supported by this terraform provider, so cant be setup in the test itself for now - singleSelectPropertyName := "single-select" // Needs to be a of type single_select, and have "option1" as an option - multiSelectPropertyName := "multi-select" // Needs to be a of type multi_select, and have "option1" and "option2" as an options - trueFlasePropertyName := "true-false" // Needs to be a of type true_false, and have "option1" as an option - stringPropertyName := "string" // Needs to be a of type string, and have "option1" as an option - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates custom property of type single_select without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + allowed_values = ["option1", "option2"] + description = "Test Description" + property_name = "%s" + value_type = "single_select" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "single_select" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["option1"] } data "github_repository_custom_properties" "test" { repository = github_repository_custom_property.test.repository } - `, randomID, singleSelectPropertyName) + `, propertyName, randomID) check := resource.ComposeTestCheckFunc( - resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", - "property.*", map[string]string{ - "property_name": singleSelectPropertyName, - "property_value.#": "1", - "property_value.0": "option1", - }), + resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", "property.*", map[string]string{ + "property_name": propertyName, + "property_value.#": "1", + "property_value.0": "option1", + }), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type multi_select without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + allowed_values = ["option1", "option2"] + description = "Test Description" + property_name = "%s" + value_type = "multi_select" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "multi_select" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["option1", "option2"] } data "github_repository_custom_properties" "test" { repository = github_repository_custom_property.test.repository } - `, randomID, multiSelectPropertyName) + `, propertyName, randomID) check := resource.ComposeTestCheckFunc( - resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", - "property.*", map[string]string{ - "property_name": multiSelectPropertyName, - "property_value.#": "2", - "property_value.0": "option1", - "property_value.1": "option2", - }), + resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", "property.*", map[string]string{ + "property_name": propertyName, + "property_value.#": "2", + "property_value.0": "option1", + "property_value.1": "option2", + }), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type true_false without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + description = "Test Description" + property_name = "%s" + value_type = "true_false" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "true_false" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["true"] } data "github_repository_custom_properties" "test" { repository = github_repository_custom_property.test.repository } - `, randomID, trueFlasePropertyName) + `, propertyName, randomID) check := resource.ComposeTestCheckFunc( - resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", - "property.*", map[string]string{ - "property_name": trueFlasePropertyName, - "property_value.#": "1", - "property_value.0": "true", - }), + resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", "property.*", map[string]string{ + "property_name": propertyName, + "property_value.#": "1", + "property_value.0": "true", + }), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type string without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + description = "Test Description" + property_name = "%s" + value_type = "string" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "string" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["text"] } data "github_repository_custom_properties" "test" { repository = github_repository_custom_property.test.repository } - `, randomID, stringPropertyName) + `, propertyName, randomID) check := resource.ComposeTestCheckFunc( - resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", - "property.*", map[string]string{ - "property_name": stringPropertyName, - "property_value.#": "1", - "property_value.0": "text", - }), + resource.TestCheckTypeSetElemNestedAttrs("data.github_repository_custom_properties.test", "property.*", map[string]string{ + "property_name": propertyName, + "property_value.#": "1", + "property_value.0": "text", + }), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_deploy_keys_test.go b/github/data_source_github_repository_deploy_keys_test.go index 8babf7e631..e89052700a 100644 --- a/github/data_source_github_repository_deploy_keys_test.go +++ b/github/data_source_github_repository_deploy_keys_test.go @@ -2,7 +2,9 @@ package github import ( "fmt" + "os/exec" "path/filepath" + "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -11,63 +13,51 @@ import ( func TestAccGithubRepositoryDeployKeysDataSource(t *testing.T) { t.Run("manages deploy keys", func(t *testing.T) { - keyPath := filepath.Join("test-fixtures", "id_rsa.pub") + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + keyName := fmt.Sprintf("%s_rsa", randomID) + cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -t rsa -b 4096 -C test@example.com -N '' -f test-fixtures/%s>/dev/null <<< y >/dev/null", keyName)) + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + + keyPath := strings.ReplaceAll(filepath.Join("test-fixtures", fmt.Sprintf("%s.pub", keyName)), "\\", "/") repoName := fmt.Sprintf("tf-acc-test-deploy-keys-%s", acctest.RandString(5)) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "%s" - auto_init = true - } - - resource "github_repository_deploy_key" "test" { - repository = github_repository.test.name - key = "${file("%s")}" - title = "title1" - } - `, repoName, keyPath) - - config2 := config + ` - data "github_repository_deploy_keys" "test" { - repository = github_repository.test.name - } - ` - - const resourceName = "data.github_repository_deploy_keys.test" - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "keys.#", "1"), - resource.TestCheckResourceAttr(resourceName, "keys.0.title", "title1"), - resource.TestCheckResourceAttrSet(resourceName, "keys.0.id"), - resource.TestCheckResourceAttr(resourceName, "keys.0.verified", "true"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, - }, - }) + resource "github_repository" "test" { + name = "%s" + auto_init = true } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + resource "github_repository_deploy_key" "test" { + repository = github_repository.test.name + key = file("%s") + title = "title1" + read_only = true + } - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + data "github_repository_deploy_keys" "test" { + repository = github_repository.test.name - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + depends_on = [github_repository_deploy_key.test] + } + `, repoName, keyPath) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_deploy_keys.test", "keys.#"), + resource.TestCheckResourceAttr("data.github_repository_deploy_keys.test", "keys.#", "1"), + resource.TestCheckResourceAttr("data.github_repository_deploy_keys.test", "keys.0.title", "title1"), + resource.TestCheckResourceAttrSet("data.github_repository_deploy_keys.test", "keys.0.id"), + resource.TestCheckResourceAttr("data.github_repository_deploy_keys.test", "keys.0.verified", "true"), + ), + }, + }, }) }) } diff --git a/github/data_source_github_repository_deployment_branch_policies_test.go b/github/data_source_github_repository_deployment_branch_policies_test.go index e6c674e2d5..983b219801 100644 --- a/github/data_source_github_repository_deployment_branch_policies_test.go +++ b/github/data_source_github_repository_deployment_branch_policies_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubRepositoryDeploymentBranchPolicies(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("queries deployment branch policies", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -46,32 +45,18 @@ func TestAccGithubRepositoryDeploymentBranchPolicies(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_repository_deployment_branch_policies.all", "deployment_branch_policies.0.id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_repository_environment_deployment_policies.go b/github/data_source_github_repository_environment_deployment_policies.go index a80e0632f6..62f8320a51 100644 --- a/github/data_source_github_repository_environment_deployment_policies.go +++ b/github/data_source_github_repository_environment_deployment_policies.go @@ -48,7 +48,7 @@ func dataSourceGithubRepositoryEnvironmentDeploymentPoliciesRead(d *schema.Resou client := meta.(*Owner).v3client owner := meta.(*Owner).name repoName := d.Get("repository").(string) - environmentName := d.Get("environment_name").(string) + environmentName := d.Get("environment").(string) policies, _, err := client.Repositories.ListDeploymentBranchPolicies(context.Background(), owner, repoName, environmentName) if err != nil { @@ -59,7 +59,7 @@ func dataSourceGithubRepositoryEnvironmentDeploymentPoliciesRead(d *schema.Resou for _, policy := range policies.BranchPolicies { policyMap := make(map[string]any) - policyMap["type"] = policy.Type + policyMap["type"] = policy.GetType() policyMap["pattern"] = policy.GetName() results = append(results, policyMap) } diff --git a/github/data_source_github_repository_environment_deployment_policies_test.go b/github/data_source_github_repository_environment_deployment_policies_test.go index 94fda8cd35..0d3d8f4a59 100644 --- a/github/data_source_github_repository_environment_deployment_policies_test.go +++ b/github/data_source_github_repository_environment_deployment_policies_test.go @@ -38,48 +38,33 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicies(t *testing.T) { environment = github_repository_environment.env.environment tag_pattern = "bar" } - `, randomID) - config2 := config + ` data "github_repository_environment_deployment_policies" "all" { repository = github_repository.test.name environment = github_repository_environment.env.environment + + depends_on = [ + github_repository_environment_deployment_policy.branch, + github_repository_environment_deployment_policy.tag, + ] } - ` + `, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.#", "2"), resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.0.type", "branch"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.0.name", "foo"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.0.pattern", "foo"), resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.1.type", "tag"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.1.name", "bar"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.all", "policies.1.pattern", "bar"), ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_environments_test.go b/github/data_source_github_repository_environments_test.go index 0c43350807..e1bc555581 100644 --- a/github/data_source_github_repository_environments_test.go +++ b/github/data_source_github_repository_environments_test.go @@ -34,32 +34,18 @@ func TestAccGithubRepositoryEnvironmentsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_repository_environments.all", "environments.0.node_id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_repository_file.go b/github/data_source_github_repository_file.go index 361587d192..4663c187ce 100644 --- a/github/data_source_github_repository_file.go +++ b/github/data_source_github_repository_file.go @@ -146,11 +146,11 @@ func dataSourceGithubRepositoryFileRead(ctx context.Context, d *schema.ResourceD } log.Printf("[DEBUG] Data Source fetching commit info for repository file: %s/%s/%s", owner, repo, file) - commit, err := getFileCommit(client, owner, repo, file, ref) - log.Printf("[DEBUG] Found file: %s/%s/%s, in commit SHA: %s ", owner, repo, file, commit.GetSHA()) + commit, err := getFileCommit(ctx, client, owner, repo, file, ref) if err != nil { return diag.FromErr(err) } + log.Printf("[DEBUG] Found file: %s/%s/%s, in commit SHA: %s ", owner, repo, file, commit.GetSHA()) if err = d.Set("commit_sha", commit.GetSHA()); err != nil { return diag.FromErr(err) diff --git a/github/data_source_github_repository_file_test.go b/github/data_source_github_repository_file_test.go index 87de418d12..1dd6ded9cb 100644 --- a/github/data_source_github_repository_file_test.go +++ b/github/data_source_github_repository_file_test.go @@ -1,32 +1,24 @@ package github import ( - "context" - "encoding/base64" - "encoding/json" "fmt" - "net/http" - "net/url" "testing" - "github.com/google/go-github/v67/github" - "github.com/stretchr/testify/assert" - - "github.com/hashicorp/terraform-plugin-sdk/v2/diag" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" ) func TestAccGithubRepositoryFileDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("create and read a file with a branch name provided", func(t *testing.T) { + t.Run("reads a file with a branch name provided without erroring", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true + + lifecycle { + ignore_changes = all + } } resource "github_repository_file" "test" { @@ -46,80 +38,96 @@ func TestAccGithubRepositoryFileDataSource(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "content", - "bar", - ), - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", - ), - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "ref", - "main", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_author", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_email", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_message", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_sha", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "id"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "ref", "main"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "content", "bar"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "sha", "ba0e162e1c47469e3fe4b393a8bf8c569f302116"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_sha"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_message"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_author"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_email"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) + }, }) + }) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + t.Run("reads a file from a short repo name without erroring", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-%s", randomID) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + auto_init = true + + lifecycle { + ignore_changes = all + } + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource "github_repository_file" "test" { + repository = github_repository.test.name + branch = "main" + file = "test" + content = "bar" + commit_message = "Managed by Terraform" + commit_author = "Terraform User" + commit_email = "terraform@example.com" + } + + data "github_repository_file" "test" { + repository = "%[1]s" + branch = "main" + file = github_repository_file.test.file + + depends_on = [github_repository_file.test] + } + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "id"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "ref", "main"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "content", "bar"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "sha", "ba0e162e1c47469e3fe4b393a8bf8c569f302116"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_sha"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_message"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_author"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_email"), + ), + }, + }, }) }) t.Run("create and read a file without providing a branch name", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true - } - - resource "github_branch" "test" { - repository = github_repository.test.name - branch = "test" - } - resource "github_branch_default" "default"{ - repository = github_repository.test.name - branch = github_branch.test.branch + lifecycle { + ignore_changes = all + } } resource "github_repository_file" "test" { repository = github_repository.test.name - branch = github_branch_default.default.branch + branch = "main" file = "test" content = "bar" commit_message = "Managed by Terraform" @@ -133,376 +141,105 @@ func TestAccGithubRepositoryFileDataSource(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "content", - "bar", - ), - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "sha", - "ba0e162e1c47469e3fe4b393a8bf8c569f302116", - ), - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "ref", - "test", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_author", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_email", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_message", - ), - resource.TestCheckResourceAttrSet( - "data.github_repository_file.test", "commit_sha", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "id"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "branch"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "ref", "main"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "content", "bar"), + resource.TestCheckResourceAttr("data.github_repository_file.test", "sha", "ba0e162e1c47469e3fe4b393a8bf8c569f302116"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_sha"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_message"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_author"), + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "commit_email"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) -} - -// TODO: This test is failing, needs review. -func TestDataSourceGithubRepositoryFileRead(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - // helper function to simplify marshalling. - marshal := func(t *testing.T, msg any) string { - data, err := json.MarshalIndent(msg, "", " ") - if err != nil { - t.Fatalf("cant encode to json: %v", err) - } - - return string(data) - } - - sha := "some-test-sha" - committerName := "some-test-user" - committerEmail := "some-test-user@github.com" - commitMessage := "test commit message" - - enc := "base64" - fileContent := "here-goes-content-of-our-glorious-config.json" - b64FileContent := base64.StdEncoding.EncodeToString([]byte(fileContent)) - - fileName := "test-file.json" - branch := "main" - - // setting up some org/owner info - owner := "test-owner" - org := "test-org" - repo := "test-repo" - - apiUrl := fmt.Sprintf("https://api.github.com/repos/%s/%s/contents/%s?ref=%s", owner, repo, fileName, branch) - - // preparing mashalled objects - repoContentRespBody := marshal(t, &github.RepositoryContent{ - Encoding: &enc, - Content: &b64FileContent, - SHA: &sha, - URL: &apiUrl, - }) - repoCommit := &github.RepositoryCommit{ - SHA: &sha, - Committer: &github.User{ - Name: &committerName, - Email: &committerEmail, - }, - Commit: &github.Commit{ - Message: &commitMessage, - }, - Files: []*github.CommitFile{ - { - Filename: &fileName, - }, - }, - } - repoCommitRespBody := marshal(t, repoCommit) - listCommitRespBody := marshal(t, []*github.RepositoryCommit{repoCommit}) - - t.Run("extracting org and repo if full_name is passed", func(t *testing.T) { - // test setup - repositoryFullName := fmt.Sprintf("%s/%s", org, repo) - expectedID := fmt.Sprintf("%s/%s", repo, fileName) - expectedRepo := "test-repo" - - ts := githubApiMock([]*mockResponse{ - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", org, repo, fileName, branch), - ResponseBody: repoContentRespBody, - StatusCode: http.StatusOK, - }, - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/commits?path=%s&sha=%s", org, repo, fileName, branch), - ResponseBody: listCommitRespBody, - StatusCode: http.StatusOK, - }, - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/commits/%s", org, repo, sha), - ResponseBody: repoCommitRespBody, - StatusCode: http.StatusOK, - }, - }) - defer ts.Close() - - httpCl := http.DefaultClient - httpCl.Transport = http.DefaultTransport - - client := github.NewClient(httpCl) - u, _ := url.Parse(ts.URL + "/") - client.BaseURL = u - - meta := &Owner{ - name: owner, - v3client: client, - } - - testSchema := map[string]*schema.Schema{ - "repository": {Type: schema.TypeString}, - "file": {Type: schema.TypeString}, - "branch": {Type: schema.TypeString}, - "commit_sha": {Type: schema.TypeString}, - "commit_email": {Type: schema.TypeString}, - "commit_author": {Type: schema.TypeString}, - "commit_message": {Type: schema.TypeString}, - "content": {Type: schema.TypeString}, - "id": {Type: schema.TypeString}, - "sha": {Type: schema.TypeString}, - "ref": {Type: schema.TypeString}, - } - - schema := schema.TestResourceDataRaw(t, testSchema, map[string]any{ - "repository": repositoryFullName, - "file": fileName, - "branch": branch, - "commit_sha": sha, - "commit_email": committerEmail, - "commit_author": committerName, - "commit_message": commitMessage, - "content": "", - "id": "", - }) - - // actual call - diags := dataSourceGithubRepositoryFileRead(context.Background(), schema, meta) - - // assertions - for _, diagnostic := range diags { - assert.Equal(t, diag.Warning, diagnostic.Severity) - } - assert.Equal(t, expectedRepo, schema.Get("repository")) - assert.Equal(t, fileContent, schema.Get("content")) - assert.Equal(t, expectedID, schema.Get("id")) - }) - t.Run("using user as owner if just name is passed", func(t *testing.T) { - // test setup - repositoryFullName := repo - expectedID := fmt.Sprintf("%s/%s", repo, fileName) - expectedRepo := "test-repo" - - ts := githubApiMock([]*mockResponse{ - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", owner, repo, fileName, branch), - ResponseBody: repoContentRespBody, - StatusCode: http.StatusOK, - }, - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/commits?path=%s&sha=%s", owner, repo, fileName, branch), - ResponseBody: listCommitRespBody, - StatusCode: http.StatusOK, - }, - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/commits/%s", owner, repo, sha), - ResponseBody: repoCommitRespBody, - StatusCode: http.StatusOK, }, }) - defer ts.Close() - - httpCl := http.DefaultClient - httpCl.Transport = http.DefaultTransport - - client := github.NewClient(httpCl) - u, _ := url.Parse(ts.URL + "/") - client.BaseURL = u - - meta := &Owner{ - name: owner, - v3client: client, - } - - testSchema := map[string]*schema.Schema{ - "repository": {Type: schema.TypeString}, - "file": {Type: schema.TypeString}, - "branch": {Type: schema.TypeString}, - "commit_sha": {Type: schema.TypeString}, - "commit_email": {Type: schema.TypeString}, - "commit_author": {Type: schema.TypeString}, - "commit_message": {Type: schema.TypeString}, - "content": {Type: schema.TypeString}, - "id": {Type: schema.TypeString}, - "sha": {Type: schema.TypeString}, - "ref": {Type: schema.TypeString}, - } - - schema := schema.TestResourceDataRaw(t, testSchema, map[string]any{ - "repository": repositoryFullName, - "file": fileName, - "branch": branch, - "commit_sha": sha, - "commit_email": committerEmail, - "commit_author": committerName, - "commit_message": commitMessage, - "content": "", - "id": "", - }) - - // actual call - diags := dataSourceGithubRepositoryFileRead(context.Background(), schema, meta) - - // assertions - for _, diagnostic := range diags { - assert.Equal(t, diag.Warning, diagnostic.Severity) - } - assert.Equal(t, expectedRepo, schema.Get("repository")) - assert.Equal(t, fileContent, schema.Get("content")) - assert.Equal(t, expectedID, schema.Get("id")) }) - t.Run("try reading a non-existent file without an error", func(t *testing.T) { + // Can't test due to SDK and test framework limitations + // t.Run("try reading a non-existent file without an error", func(t *testing.T) { + // randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "tf-acc-test-%s" + // auto_init = true + + // lifecycle { + // ignore_changes = all + // } + // } + + // data "github_repository_file" "test" { + // repository = github_repository.test.name + // file = "test" + // } + // `, randomID) + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // Config: config, + // Check: resource.ComposeTestCheckFunc( + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "id"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "branch"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "ref"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "content"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "sha"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_sha"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_message"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_author"), + // resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_email"), + // ), + // }, + // }, + // }) + // }) + + t.Run("reads a directory without erroring", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true + + lifecycle { + ignore_changes = all + } } data "github_repository_file" "test" { repository = github_repository.test.name - file = "test" + file = "." } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_repository_file.test", "id", "", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_file.test", "id"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "ref"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "content"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "sha"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_sha"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_message"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_author"), + resource.TestCheckNoResourceAttr("data.github_repository_file.test", "commit_email"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) - - repoContentDirectoryRespBody := marshal(t, []github.RepositoryContent{ - { - Encoding: &enc, - Content: &b64FileContent, - SHA: &sha, - URL: &apiUrl, - }, - }) - - t.Run("extract only non-file data if the path is for a directory", func(t *testing.T) { - // test setup - repositoryFullName := fmt.Sprintf("%s/%s", org, repo) - - expectedID := fmt.Sprintf("%s/%s", repo, fileName) - expectedRepo := "test-repo" - - ts := githubApiMock([]*mockResponse{ - { - ExpectedUri: fmt.Sprintf("/repos/%s/%s/contents/%s?ref=%s", org, repo, fileName, branch), - ResponseBody: repoContentDirectoryRespBody, - StatusCode: http.StatusOK, }, }) - defer ts.Close() - - httpCl := http.DefaultClient - httpCl.Transport = http.DefaultTransport - - client := github.NewClient(httpCl) - u, _ := url.Parse(ts.URL + "/") - client.BaseURL = u - - meta := &Owner{ - name: owner, - v3client: client, - } - - testSchema := map[string]*schema.Schema{ - "repository": {Type: schema.TypeString}, - "file": {Type: schema.TypeString}, - "branch": {Type: schema.TypeString}, - "commit_sha": {Type: schema.TypeString}, - "content": {Type: schema.TypeString}, - "id": {Type: schema.TypeString}, - } - - schema := schema.TestResourceDataRaw(t, testSchema, map[string]any{ - "repository": repositoryFullName, - "file": fileName, - "branch": branch, - "commit_sha": sha, - }) - - // actual call - diags := dataSourceGithubRepositoryFileRead(context.Background(), schema, meta) - - // assertions - for _, diagnostic := range diags { - assert.Equal(t, diagnostic.Severity, diag.Warning) - } - assert.Equal(t, expectedRepo, schema.Get("repository")) - assert.Equal(t, expectedID, schema.Get("id")) - assert.Equal(t, "", schema.Get("content")) - assert.Equal(t, nil, schema.Get("sha")) }) } diff --git a/github/data_source_github_repository_milestone_test.go b/github/data_source_github_repository_milestone_test.go index 1cbfdb4631..562f6b8333 100644 --- a/github/data_source_github_repository_milestone_test.go +++ b/github/data_source_github_repository_milestone_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubRepositoryMilestoneDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("queries a repository milestone", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -43,29 +42,15 @@ func TestAccGithubRepositoryMilestoneDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_pull_request.go b/github/data_source_github_repository_pull_request.go index 9cc4756f8b..a878c05f14 100644 --- a/github/data_source_github_repository_pull_request.go +++ b/github/data_source_github_repository_pull_request.go @@ -91,7 +91,7 @@ func dataSourceGithubRepositoryPullRequest() *schema.Resource { } func dataSourceGithubRepositoryPullRequestRead(d *schema.ResourceData, meta any) error { - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name diff --git a/github/data_source_github_repository_pull_request_test.go b/github/data_source_github_repository_pull_request_test.go index 14057e0197..2568e15a84 100644 --- a/github/data_source_github_repository_pull_request_test.go +++ b/github/data_source_github_repository_pull_request_test.go @@ -68,29 +68,15 @@ func TestAccGithubRepositoryPullRequestDataSource(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_pull_requests.go b/github/data_source_github_repository_pull_requests.go index f5b3582ddd..775fa04522 100644 --- a/github/data_source_github_repository_pull_requests.go +++ b/github/data_source_github_repository_pull_requests.go @@ -129,7 +129,7 @@ func dataSourceGithubRepositoryPullRequests() *schema.Resource { } func dataSourceGithubRepositoryPullRequestsRead(d *schema.ResourceData, meta any) error { - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name diff --git a/github/data_source_github_repository_pull_requests_test.go b/github/data_source_github_repository_pull_requests_test.go index 5403820b49..69430b17ad 100644 --- a/github/data_source_github_repository_pull_requests_test.go +++ b/github/data_source_github_repository_pull_requests_test.go @@ -78,29 +78,15 @@ func TestAccGithubRepositoryPullRequestsDataSource(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "results.0.updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_teams.go b/github/data_source_github_repository_teams.go index cf7d66aa31..4006daab04 100644 --- a/github/data_source_github_repository_teams.go +++ b/github/data_source_github_repository_teams.go @@ -51,6 +51,7 @@ func dataSourceGithubRepositoryTeams() *schema.Resource { } func dataSourceGithubTeamsRead(d *schema.ResourceData, meta any) error { + ctx := context.Background() client := meta.(*Owner).v3client owner := meta.(*Owner).name var repoName string @@ -77,7 +78,7 @@ func dataSourceGithubTeamsRead(d *schema.ResourceData, meta any) error { var all_teams []map[string]string for { - teams, resp, err := client.Repositories.ListTeams(context.TODO(), owner, repoName, &options) + teams, resp, err := client.Repositories.ListTeams(ctx, owner, repoName, &options) if err != nil { return err } diff --git a/github/data_source_github_repository_teams_test.go b/github/data_source_github_repository_teams_test.go index 7554dae05e..f7f1525325 100644 --- a/github/data_source_github_repository_teams_test.go +++ b/github/data_source_github_repository_teams_test.go @@ -42,25 +42,19 @@ func TestAccGithubRepositoryTeamsDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_repository_teams.test", "teams.0.permission", "push"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(), }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_repository_test.go b/github/data_source_github_repository_test.go index 6c51df8062..c51d6bdba9 100644 --- a/github/data_source_github_repository_test.go +++ b/github/data_source_github_repository_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,41 +9,78 @@ import ( ) func TestAccGithubRepositoryDataSource(t *testing.T) { - t.Run("anonymously queries a repository without error", func(t *testing.T) { + t.Run("queries a public repository without error", func(t *testing.T) { config := fmt.Sprintf(` - data "github_repositories" "test" { - query = "org:%s" + data "github_repository" "test" { + full_name = "%s/%s" } + `, testAccConf.testPublicRepositoryOwner, testAccConf.testPublicRepository) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "data.github_repository.test", "full_name", + fmt.Sprintf("%s/%s", testAccConf.testPublicRepositoryOwner, testAccConf.testPublicRepository)), + ) + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) + + t.Run("queries repository belonging to the current user without error", func(t *testing.T) { + if len(testAccConf.testUserRepository) == 0 { + t.Skip("No test user repository provided") + } + config := fmt.Sprintf(` data "github_repository" "test" { - full_name = data.github_repositories.test.full_names.0 + full_name = "%s/%s" } - `, testOrganization) + `, testAccConf.username, testAccConf.testUserRepository) check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "data.github_repositories.test", "full_names.0", - regexp.MustCompile(`^`+testOrganization)), - resource.TestMatchResourceAttr( + resource.TestCheckResourceAttr( "data.github_repository.test", "full_name", - regexp.MustCompile(`^`+testOrganization)), + fmt.Sprintf("%s/%s", testAccConf.username, testAccConf.testUserRepository)), ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } + }, + }) + }) + + t.Run("queries an org repository without error", func(t *testing.T) { + config := fmt.Sprintf(` + data "github_repository" "test" { + full_name = "%s/%s" + } + `, testAccConf.owner, testAccConf.testOrgRepository) - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "data.github_repository.test", "full_name", + fmt.Sprintf("%s/%s", testAccConf.owner, testAccConf.testOrgRepository)), + ) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) }) @@ -74,109 +110,61 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("checks defaults on a new repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-%s", randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" auto_init = true } data "github_repository" "test" { name = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_repository.test", "name", "tf-acc-"+randomID, - ), - resource.TestCheckResourceAttrSet( - "data.github_repository.test", "has_projects", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "description", "", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "homepage_url", "", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "pages.#", "0", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "fork", "false", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "allow_update_branch", "true", - ), - resource.TestCheckResourceAttr( - "data.github_repository.test", "delete_branch_on_merge", "true", - ), + resource.TestCheckResourceAttr("data.github_repository.test", "name", repoName), + resource.TestCheckResourceAttrSet("data.github_repository.test", "has_projects"), + resource.TestCheckResourceAttr("data.github_repository.test", "description", ""), + resource.TestCheckResourceAttr("data.github_repository.test", "homepage_url", ""), + resource.TestCheckResourceAttr("data.github_repository.test", "pages.#", "0"), + resource.TestCheckResourceAttr("data.github_repository.test", "fork", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("queries a repository that is a template", func(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - + t.Run("queries a public repository that is a template", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - is_template = true - } - data "github_repository" "test" { - name = github_repository.test.name + full_name = "%s/%s" } - `, randomID) + `, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -185,29 +173,45 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) + }, + }) + }) + + t.Run("queries an org repository that is a template", func(t *testing.T) { + if len(testAccConf.testOrgTemplateRepository) == 0 { + t.Skip("No org template repository provided") } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + config := fmt.Sprintf(` + data "github_repository" "test" { + full_name = "%s/%s" + } + `, testAccConf.owner, testAccConf.testOrgTemplateRepository) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "data.github_repository.test", "is_template", + "true", + ), + ) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) }) @@ -218,15 +222,15 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { resource "github_repository" "test" { name = "tf-acc-%s" template { - owner = "template-repository" - repository = "template-repository" + owner = "%s" + repository = "%s" } } data "github_repository" "test" { name = github_repository.test.name } - `, randomID) + `, randomID, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -239,29 +243,15 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -285,88 +275,58 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("queries a repository that has go as primary_language", func(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - } - resource "github_repository_file" "test" { - repository = github_repository.test.name - file = "test.go" - content = "package main" - } - - data "github_repository" "test" { - name = github_repository_file.test.repository - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "data.github_repository.test", "primary_language", - "Go", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - // Not doing any checks since the language doesnt have time to be updated on the first apply - Config: config, - }, - { - // Re-running the terraform will refresh the language since the go-file has been created - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + // t.Run("queries a repository that has go as primary_language", func(t *testing.T) { + // randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "tf-acc-%s" + // auto_init = true + // } + // resource "github_repository_file" "test" { + // repository = github_repository.test.name + // file = "test.go" + // content = "package main" + // } + + // data "github_repository" "test" { + // name = github_repository_file.test.repository + // depends_on = [github_repository_file.test] + // } + // `, randomID) + + // check := resource.ComposeTestCheckFunc( + // resource.TestCheckResourceAttr("data.github_repository.test", "primary_language", "Go"), + // ) + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // // Not doing any checks since the language doesnt have time to be updated on the first apply + // Config: config, + // }, + // { + // // Re-running the terraform will refresh the language since the go-file has been created + // Config: config, + // Check: check, + // }, + // }, + // }) + // }) t.Run("queries a repository that has a license", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) @@ -403,29 +363,15 @@ EOT ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_repository_webhooks_test.go b/github/data_source_github_repository_webhooks_test.go index 55c9f563e7..e14a687f40 100644 --- a/github/data_source_github_repository_webhooks_test.go +++ b/github/data_source_github_repository_webhooks_test.go @@ -13,66 +13,46 @@ func TestAccGithubRepositoryWebhooksDataSource(t *testing.T) { repoName := fmt.Sprintf("tf-acc-test-webhooks-%s", acctest.RandString(5)) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "%s" - auto_init = true - } - - resource "github_repository_webhook" "test" { - repository = github_repository.test.name - - configuration { - url = "https://google.de/webhook" - content_type = "json" - insecure_ssl = true - } + resource "github_repository" "test" { + name = "%s" + auto_init = true + } - events = ["pull_request"] - } - `, repoName) + resource "github_repository_webhook" "test" { + repository = github_repository.test.name - config2 := config + ` - data "github_repository_webhooks" "test" { - repository = github_repository.test.name + configuration { + url = "https://google.de/webhook" + content_type = "json" + insecure_ssl = true } - ` - - const resourceName = "data.github_repository_webhooks.test" - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "webhooks.#", "1"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.name", "web"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.url", "https://google.de/webhook"), - resource.TestCheckResourceAttr(resourceName, "webhooks.0.active", "true"), - resource.TestCheckResourceAttrSet(resourceName, "webhooks.0.id"), - ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, - }, - }) + events = ["pull_request"] } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + data "github_repository_webhooks" "test" { + repository = github_repository.test.name - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + depends_on = [github_repository_webhook.test] + } + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("data.github_repository_webhooks.test", "webhooks.#"), + resource.TestCheckResourceAttr("data.github_repository_webhooks.test", "webhooks.#", "1"), + resource.TestCheckResourceAttrSet("data.github_repository_webhooks.test", "webhooks.0.id"), + resource.TestCheckResourceAttr("data.github_repository_webhooks.test", "webhooks.0.name", "web"), + resource.TestCheckResourceAttr("data.github_repository_webhooks.test", "webhooks.0.active", "true"), + resource.TestCheckResourceAttrSet("data.github_repository_webhooks.test", "webhooks.0.url"), + ), + }, + }, }) }) } diff --git a/github/data_source_github_rest_api_test.go b/github/data_source_github_rest_api_test.go index 4973b5dd84..8469394ab8 100644 --- a/github/data_source_github_rest_api_test.go +++ b/github/data_source_github_rest_api_test.go @@ -3,7 +3,6 @@ package github import ( "fmt" "regexp" - "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -36,29 +35,15 @@ func TestAccGithubRestApiDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_rest_api.test", "headers"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -78,29 +63,15 @@ func TestAccGithubRestApiDataSource(t *testing.T) { resource.TestMatchResourceAttr("data.github_rest_api.test", "body", regexp.MustCompile(`\[.*refs/heads/.*\]`)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -127,64 +98,34 @@ func TestAccGithubRestApiDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_rest_api.test", "headers"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("fails for invalid endpoint", func(t *testing.T) { - // 4096 characters is the maximum length for a URL - endpoint := strings.Repeat("x", 4096) - config := fmt.Sprintf(` - data "github_rest_api" "test" { - endpoint = "/%v" - } - `, endpoint) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile("Error: GET https://api.github.com/xx.*: 414"), - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + // t.Run("fails for invalid endpoint", func(t *testing.T) { + // config := ` + // data "github_rest_api" "test" { + // endpoint = "/xxx" + // } + // ` + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // Config: config, + // ExpectError: regexp.MustCompile("Error: GET https://api.github.com/xx.*: 414"), + // }, + // }, + // }) + // }) } diff --git a/github/data_source_github_ssh_keys_test.go b/github/data_source_github_ssh_keys_test.go index 5dce951223..372045dea4 100644 --- a/github/data_source_github_ssh_keys_test.go +++ b/github/data_source_github_ssh_keys_test.go @@ -14,29 +14,14 @@ func TestAccGithubSshKeysDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_ssh_keys.test", "keys.#"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_team_repository_test.go b/github/data_source_github_team_repository_test.go deleted file mode 100644 index 953f023b28..0000000000 --- a/github/data_source_github_team_repository_test.go +++ /dev/null @@ -1,67 +0,0 @@ -package github - -import ( - "fmt" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestAccGithubTeamRepositories(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("Get Repositories By Teams", func(t *testing.T) { - config := fmt.Sprintf(` - - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } - - resource "github_team" "test" { - name = "tf-acc-test-%[1]s" - } - - resource "github_team_repository" "test" { - team_id = "${github_team.test.id}" - repository = "${github_repository.test.name}" - } - - data "github_team" "example" { - depends_on = ["github_repository.test", "github_team.test", "github_team_repository.test"] - slug = github_team.test.slug - } - `, randomID) - - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr("data.github_team.example", "repositories.#", "1"), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - ExpectNonEmptyPlan: true, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) -} diff --git a/github/data_source_github_team_test.go b/github/data_source_github_team_test.go index 9c644013cc..9696431ae8 100644 --- a/github/data_source_github_team_test.go +++ b/github/data_source_github_team_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubTeamDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("queries an existing team without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-%s" @@ -28,33 +27,20 @@ func TestAccGithubTeamDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_team.test", "node_id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("queries an existing team without error with immediate membership", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-%s" @@ -71,29 +57,15 @@ func TestAccGithubTeamDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_team.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -104,33 +76,20 @@ func TestAccGithubTeamDataSource(t *testing.T) { } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`Not Found`), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`Not Found`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("queries an existing team without error in summary_only mode", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-%s" @@ -149,33 +108,20 @@ func TestAccGithubTeamDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_team.test", "repositories.#", "0"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("queries an existing team without error with results_per_page reduced", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-%s" @@ -192,33 +138,72 @@ func TestAccGithubTeamDataSource(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_team.test", "node_id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) + }, + }) + }) + + t.Run("get team with repositories without erroring", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + resource "github_team" "test" { + name = "tf-acc-test-%[1]s" + } - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "admin" + } + + data "github_team" "test" { + slug = github_team.test.slug - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + depends_on = [github_repository.test, github_team.test, github_team_repository.test] + } + `, randomID) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrPair("data.github_team.test", "id", "github_team.test", "id"), + resource.TestCheckResourceAttrPair("data.github_team.test", "node_id", "github_team.test", "node_id"), + resource.TestCheckResourceAttrPair("data.github_team.test", "slug", "github_team.test", "slug"), + resource.TestCheckResourceAttrPair("data.github_team.test", "name", "github_team.test", "name"), + resource.TestCheckResourceAttrPair("data.github_team.test", "description", "github_team.test", "description"), + resource.TestCheckResourceAttrPair("data.github_team.test", "privacy", "github_team.test", "privacy"), + resource.TestCheckResourceAttrSet("data.github_team.test", "repositories.#"), + resource.TestCheckResourceAttr("data.github_team.test", "repositories.#", "1"), + resource.TestCheckResourceAttrPair("data.github_team.test", "repositories.0", "github_repository.test", "name"), + resource.TestCheckResourceAttrSet("data.github_team.test", "repositories_detailed.#"), + resource.TestCheckResourceAttr("data.github_team.test", "repositories_detailed.#", "1"), + resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.repo_id", "github_repository.test", "repo_id"), + resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.repo_name", "github_repository.test", "name"), + resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.role_name", "github_team_repository.test", "permission"), + ), + }, + }, }) }) t.Run("queries an existing team with connected repositories", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-%s" @@ -244,36 +229,23 @@ func TestAccGithubTeamDataSource(t *testing.T) { resource.TestCheckResourceAttr("github_repository.test", "name", "tf-acc-test"), resource.TestCheckResourceAttr("data.github_team.test", "repositories_detailed.#", "1"), resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.repo_id", "github_repository.test", "repo_id"), + resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.repo_name", "github_repository.test", "name"), resource.TestCheckResourceAttrPair("data.github_team.test", "repositories_detailed.0.role_name", "github_team_repository.test", "permission"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeAggregateTestCheckFunc(), - }, - { - Config: config2, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc(), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check, + }, + }, }) }) } diff --git a/github/data_source_github_tree_test.go b/github/data_source_github_tree_test.go index e5b5f78358..25fb86818d 100644 --- a/github/data_source_github_tree_test.go +++ b/github/data_source_github_tree_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubTreeDataSource(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("get tree", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "this" { auto_init = true @@ -44,29 +43,15 @@ func TestAccGithubTreeDataSource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_user_external_identity_test.go b/github/data_source_github_user_external_identity_test.go index ad6dda456a..8a48c7cd68 100644 --- a/github/data_source_github_user_external_identity_test.go +++ b/github/data_source_github_user_external_identity_test.go @@ -7,16 +7,8 @@ import ( ) func TestAccGithubUserExternalIdentity(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - t.Run("queries without error", func(t *testing.T) { - config := ` - data "github_user_external_identity" "test" { - - - }` + config := `data "github_user_external_identity" "test" {}` check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_user_external_identity.test", "login"), @@ -24,28 +16,15 @@ func TestAccGithubUserExternalIdentity(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_user_external_identity.test", "scim_identity.username"), ) - testCase := func(t *testing.T) { - resource.Test(t, resource.TestCase{ - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an user accoy", func(t *testing.T) { - testCase(t) + }, }) }) } diff --git a/github/data_source_github_user_test.go b/github/data_source_github_user_test.go index cdb592af5e..1c2cf63f62 100644 --- a/github/data_source_github_user_test.go +++ b/github/data_source_github_user_test.go @@ -9,41 +9,31 @@ import ( ) func TestAccGithubUserDataSource(t *testing.T) { + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") + } + t.Run("queries an existing individual account without error", func(t *testing.T) { config := fmt.Sprintf(` data "github_user" "test" { username = "%s" } - `, testOwnerFunc()) + `, testAccConf.testExternalUser) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_user.test", "login"), resource.TestCheckResourceAttrSet("data.github_user.test", "id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -52,31 +42,17 @@ func TestAccGithubUserDataSource(t *testing.T) { data "github_user" "test" { username = "!%s" } - `, testOwnerFunc()) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`Not Found`), - }, + `, testAccConf.testExternalUser) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`Not Found`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/data_source_github_users_test.go b/github/data_source_github_users_test.go index 7fbe5f852a..3d60e7bcdc 100644 --- a/github/data_source_github_users_test.go +++ b/github/data_source_github_users_test.go @@ -9,44 +9,34 @@ import ( // TODO: this is failing. func TestAccGithubUsersDataSource(t *testing.T) { + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") + } + t.Run("queries multiple accounts", func(t *testing.T) { config := fmt.Sprintf(` data "github_users" "test" { usernames = ["%[1]s", "!%[1]s"] } - `, testOwnerFunc()) + `, testAccConf.testExternalUser) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("data.github_users.test", "logins.#", "1"), - resource.TestCheckResourceAttr("data.github_users.test", "logins.0", testOwnerFunc()), + resource.TestCheckResourceAttr("data.github_users.test", "logins.0", testAccConf.testExternalUser), resource.TestCheckResourceAttr("data.github_users.test", "node_ids.#", "1"), resource.TestCheckResourceAttr("data.github_users.test", "unknown_logins.#", "1"), - resource.TestCheckResourceAttr("data.github_users.test", "unknown_logins.0", fmt.Sprintf("!%s", testOwnerFunc())), + resource.TestCheckResourceAttr("data.github_users.test", "unknown_logins.0", fmt.Sprintf("!%s", testAccConf.testExternalUser)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -63,29 +53,15 @@ func TestAccGithubUsersDataSource(t *testing.T) { resource.TestCheckResourceAttr("data.github_users.test", "unknown_logins.#", "0"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/provider.go b/github/provider.go index 57f1da449e..46502d4d22 100644 --- a/github/provider.go +++ b/github/provider.go @@ -354,7 +354,7 @@ func providerConfigure(p *schema.Provider) schema.ConfigureContextFunc { // an explicitly set value in a provider block), but is necessary // for backwards compatibility. We could remove this backwards compatibility // code in a future major release. - env, _ := OwnerOrOrgEnvDefaultFunc() + env := ownerOrOrgEnvDefaultFunc() if env.(string) != "" { owner = env.(string) } @@ -529,3 +529,13 @@ func tokenFromGHCLI(u *url.URL) string { log.Printf("[INFO] Using the token from GitHub CLI") return strings.TrimSpace(string(out)) } + +func ownerOrOrgEnvDefaultFunc() any { + if organization := os.Getenv("GITHUB_ORGANIZATION"); organization != "" { + log.Printf("[INFO] Selecting owner %s from GITHUB_ORGANIZATION environment variable", organization) + return organization + } + owner := os.Getenv("GITHUB_OWNER") + log.Printf("[INFO] Selecting owner %s from GITHUB_OWNER environment variable", owner) + return owner +} diff --git a/github/provider_test.go b/github/provider_test.go index f5692810ad..3f6a78791c 100644 --- a/github/provider_test.go +++ b/github/provider_test.go @@ -49,19 +49,21 @@ func TestProvider(t *testing.T) { }) } -// TODO: this is failing. func TestAccProviderConfigure(t *testing.T) { t.Run("can be configured to run anonymously", func(t *testing.T) { config := ` - provider "github" {} + provider "github" { + token = "" + } + data "github_ip_ranges" "test" {} ` resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, anonymous) }, - Providers: testAccProviders, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, + PlanOnly: true, ExpectNonEmptyPlan: false, }, }, @@ -69,20 +71,20 @@ func TestAccProviderConfigure(t *testing.T) { }) t.Run("can be configured to run insecurely", func(t *testing.T) { - config := fmt.Sprintf(` - provider "github" { - token = "%s" - insecure = true - }`, - testToken, - ) + config := ` + provider "github" { + token = "" + insecure = true + } + data "github_ip_ranges" "test" {} + ` resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, anonymous) }, - Providers: testAccProviders, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, + PlanOnly: true, ExpectNonEmptyPlan: false, }, }, @@ -94,16 +96,16 @@ func TestAccProviderConfigure(t *testing.T) { provider "github" { token = "%s" owner = "%s" - }`, - testToken, testOwnerFunc(), - ) + } + `, testAccConf.token, testAccConf.owner) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, individual) }, - Providers: testAccProviders, + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, + PlanOnly: true, ExpectNonEmptyPlan: false, }, }, @@ -114,21 +116,40 @@ func TestAccProviderConfigure(t *testing.T) { config := fmt.Sprintf(` provider "github" { token = "%s" - organization = "%s" - }`, - testToken, testOrganizationFunc(), - ) + owner = "%s" + }`, testAccConf.token, testAccConf.owner) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, - Providers: testAccProviders, + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, + PlanOnly: true, ExpectNonEmptyPlan: false, }, }, }) + + t.Run("can be configured with an organization account legacy", func(t *testing.T) { + config := fmt.Sprintf(` + provider "github" { + token = "%s" + organization = "%s" + }`, testAccConf.token, testAccConf.owner) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + PlanOnly: true, + ExpectNonEmptyPlan: false, + }, + }, + }) + }) }) t.Run("can be configured with a GHES deployment", func(t *testing.T) { @@ -136,13 +157,11 @@ func TestAccProviderConfigure(t *testing.T) { provider "github" { token = "%s" base_url = "%s" - }`, - testToken, testBaseURLGHES, - ) + }`, testAccConf.token, testAccConf.owner) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, individual) }, - Providers: testAccProviders, + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, @@ -155,16 +174,13 @@ func TestAccProviderConfigure(t *testing.T) { t.Run("can be configured with max retries", func(t *testing.T) { config := fmt.Sprintf(` provider "github" { - token = "%s" owner = "%s" max_retries = 3 - }`, - testToken, testOwnerFunc(), - ) + }`, testAccConf.owner) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, individual) }, - Providers: testAccProviders, + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, @@ -175,25 +191,22 @@ func TestAccProviderConfigure(t *testing.T) { }) t.Run("can be configured with max per page", func(t *testing.T) { - config := fmt.Sprintf(` + config := ` provider "github" { - token = "%s" owner = "%s" - max_per_page = 999 - }`, - testToken, testOwnerFunc(), - ) + max_per_page = 100 + }` resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, individual) }, - Providers: testAccProviders, + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, ExpectNonEmptyPlan: false, Check: func(_ *terraform.State) error { - if maxPerPage != 999 { - return fmt.Errorf("max_per_page should be set to 999, got %d", maxPerPage) + if maxPerPage != 100 { + return fmt.Errorf("max_per_page should be set to 100, got %d", maxPerPage) } return nil }, diff --git a/github/provider_utils.go b/github/provider_utils.go deleted file mode 100644 index 386a4e4407..0000000000 --- a/github/provider_utils.go +++ /dev/null @@ -1,140 +0,0 @@ -package github - -import ( - "fmt" - "log" - "os" - "testing" -) - -var ( - testCollaborator = os.Getenv("GITHUB_TEST_COLLABORATOR") - isEnterprise = os.Getenv("ENTERPRISE_ACCOUNT") - isPaidPlan = os.Getenv("GITHUB_PAID_FEATURES") - testEnterprise = os.Getenv("ENTERPRISE_SLUG") - testOrganization = testOrganizationFunc() - testOwner = os.Getenv("GITHUB_OWNER") - testToken = os.Getenv("GITHUB_TOKEN") - testBaseURLGHES = os.Getenv("GHES_BASE_URL") -) - -func testAccPreCheck(t *testing.T) { - if v := os.Getenv("GITHUB_TOKEN"); v == "" { - t.Fatal("GITHUB_TOKEN must be set for acceptance tests") - } - if v := os.Getenv("GITHUB_ORGANIZATION"); v == "" && os.Getenv("GITHUB_OWNER") == "" { - t.Fatal("GITHUB_ORGANIZATION or GITHUB_OWNER must be set for acceptance tests") - } - if v := os.Getenv("GITHUB_TEST_USER"); v == "" { - t.Fatal("GITHUB_TEST_USER must be set for acceptance tests") - } - if v := os.Getenv("GITHUB_TEST_COLLABORATOR"); v == "" { - t.Fatal("GITHUB_TEST_COLLABORATOR must be set for acceptance tests") - } - if v := os.Getenv("GITHUB_TEMPLATE_REPOSITORY"); v == "" { - t.Fatal("GITHUB_TEMPLATE_REPOSITORY must be set for acceptance tests") - } - if v := os.Getenv("GITHUB_TEMPLATE_REPOSITORY_RELEASE_ID"); v == "" { - t.Fatal("GITHUB_TEMPLATE_REPOSITORY_RELEASE_ID must be set for acceptance tests") - } -} - -func skipUnlessMode(t *testing.T, providerMode string) { - switch providerMode { - case anonymous: - if os.Getenv("GITHUB_BASE_URL") != "" && - os.Getenv("GITHUB_BASE_URL") != "https://api.github.com/" { - t.Log("anonymous mode not supported for GHES deployments") - break - } - - if os.Getenv("GITHUB_TOKEN") == "" { - return - } else { - t.Log("GITHUB_TOKEN environment variable should be empty") - } - case enterprise: - if os.Getenv("GITHUB_TOKEN") == "" { - t.Log("GITHUB_TOKEN environment variable should be set") - } else { - return - } - - case individual: - if os.Getenv("GITHUB_TOKEN") != "" && os.Getenv("GITHUB_OWNER") != "" { - return - } else { - t.Log("GITHUB_TOKEN and GITHUB_OWNER environment variables should be set") - } - case organization: - if os.Getenv("GITHUB_TOKEN") != "" && os.Getenv("GITHUB_ORGANIZATION") != "" { - return - } else { - t.Log("GITHUB_TOKEN and GITHUB_ORGANIZATION environment variables should be set") - } - } - - t.Skipf("Skipping %s which requires %s mode", t.Name(), providerMode) -} - -func testAccCheckOrganization() error { - baseURL := os.Getenv("GITHUB_BASE_URL") - token := os.Getenv("GITHUB_TOKEN") - - owner := os.Getenv("GITHUB_OWNER") - if owner == "" { - organization := os.Getenv("GITHUB_ORGANIZATION") - if organization == "" { - return fmt.Errorf("neither `GITHUB_OWNER` or `GITHUB_ORGANIZATION` set in environment") - } - owner = organization - } - - config := Config{ - BaseURL: baseURL, - Token: token, - Owner: owner, - } - - meta, err := config.Meta() - if err != nil { - return err - } - if !meta.(*Owner).IsOrganization { - return fmt.Errorf("configured owner %q is a user, not an organization", meta.(*Owner).name) - } - return nil -} - -func OwnerOrOrgEnvDefaultFunc() (any, error) { - if organization := os.Getenv("GITHUB_ORGANIZATION"); organization != "" { - log.Printf("[INFO] Selecting owner %s from GITHUB_ORGANIZATION environment variable", organization) - return organization, nil - } - owner := os.Getenv("GITHUB_OWNER") - log.Printf("[INFO] Selecting owner %s from GITHUB_OWNER environment variable", owner) - return owner, nil -} - -func testOrganizationFunc() string { - organization := os.Getenv("GITHUB_ORGANIZATION") - if organization == "" { - organization = os.Getenv("GITHUB_TEST_ORGANIZATION") - } - return organization -} - -func testOwnerFunc() string { - owner := os.Getenv("GITHUB_OWNER") - if owner == "" { - owner = os.Getenv("GITHUB_TEST_OWNER") - } - return owner -} - -const ( - anonymous = "anonymous" - individual = "individual" - organization = "organization" - enterprise = "enterprise" -) diff --git a/github/repository_utils.go b/github/repository_utils.go index 89e31a5067..12d051296b 100644 --- a/github/repository_utils.go +++ b/github/repository_utils.go @@ -28,8 +28,7 @@ func checkRepositoryBranchExists(client *github.Client, owner, repo, branch stri return nil } -func getFileCommit(client *github.Client, owner, repo, file, branch string) (*github.RepositoryCommit, error) { - ctx := context.WithValue(context.Background(), ctxId, fmt.Sprintf("%s/%s", repo, file)) +func getFileCommit(ctx context.Context, client *github.Client, owner, repo, file, branch string) (*github.RepositoryCommit, error) { opts := &github.CommitsListOptions{ SHA: branch, Path: file, diff --git a/github/resource_github_actions_environment_secret_test.go b/github/resource_github_actions_environment_secret_test.go index 6a203631f5..00e4f5a6df 100644 --- a/github/resource_github_actions_environment_secret_test.go +++ b/github/resource_github_actions_environment_secret_test.go @@ -12,9 +12,8 @@ import ( ) func TestAccGithubActionsEnvironmentSecret(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) @@ -78,39 +77,26 @@ func TestAccGithubActionsEnvironmentSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) t.Run("deletes secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) config := fmt.Sprintf(` @@ -138,29 +124,15 @@ func TestAccGithubActionsEnvironmentSecret(t *testing.T) { } `, randomID, secretValue, secretValue) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } @@ -250,49 +222,35 @@ func TestAccGithubActionsEnvironmentSecretIgnoreChanges(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: fmt.Sprintf(configFmtStr, randomID, secretValue, secretValue), - Check: checks["before"], - }, - { - Config: fmt.Sprintf(configFmtStr, randomID, secretValue, secretValue), - Check: checks["after"], - }, - { - // In this case the values change in the config, but the lifecycle ignore_changes should - // not cause the actual values to be updated. This would also be the case when a secret - // is externally modified (when what is in state does not match what is given). - Config: fmt.Sprintf(configFmtStr, randomID, modifiedSecretValue, modifiedSecretValue), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_actions_environment_secret.plaintext_secret", "plaintext_value", - secretValue, // Should still have the original value in state. - ), - resource.TestCheckResourceAttr( - "github_actions_environment_secret.encrypted_secret", "encrypted_value", - secretValue, // Should still have the original value in state. - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: fmt.Sprintf(configFmtStr, randomID, secretValue, secretValue), + Check: checks["before"], + }, + { + Config: fmt.Sprintf(configFmtStr, randomID, secretValue, secretValue), + Check: checks["after"], + }, + { + // In this case the values change in the config, but the lifecycle ignore_changes should + // not cause the actual values to be updated. This would also be the case when a secret + // is externally modified (when what is in state does not match what is given). + Config: fmt.Sprintf(configFmtStr, randomID, modifiedSecretValue, modifiedSecretValue), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_actions_environment_secret.plaintext_secret", "plaintext_value", + secretValue, // Should still have the original value in state. + ), + resource.TestCheckResourceAttr( + "github_actions_environment_secret.encrypted_secret", "encrypted_value", + secretValue, // Should still have the original value in state. ), - }, + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_environment_variable_test.go b/github/resource_github_actions_environment_variable_test.go index ca954b91ae..05ee1bcedc 100644 --- a/github/resource_github_actions_environment_variable_test.go +++ b/github/resource_github_actions_environment_variable_test.go @@ -14,9 +14,8 @@ import ( ) func TestAccGithubActionsEnvironmentVariable(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates environment variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) value := "my_variable_value" updatedValue := "my_updated_variable_value" @@ -65,39 +64,26 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - value, - updatedValue, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + value, + updatedValue, 1), + Check: checks["after"], + }, + }, }) }) t.Run("deletes environment variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -116,33 +102,20 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports environment variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) value := "my_variable_value" envName := "environment / test" varName := "test_variable" @@ -165,34 +138,20 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { } `, randomID, envName, varName, value) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - ResourceName: "github_actions_environment_variable.variable", - ImportStateId: fmt.Sprintf(`tf-acc-test-%s:%s:%s`, randomID, envName, varName), - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_environment_variable.variable", + ImportStateId: fmt.Sprintf(`tf-acc-test-%s:%s:%s`, randomID, envName, varName), + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } @@ -223,16 +182,13 @@ func TestAccGithubActionsEnvironmentVariable_alreadyExists(t *testing.T) { } `, repoName, envName, varName, value) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { - skipUnlessMode(t, mode) - }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - // First, create the repository and environment. - Config: fmt.Sprintf(` + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + // First, create the repository and environment. + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "%s" vulnerability_alerts = true @@ -243,39 +199,30 @@ func TestAccGithubActionsEnvironmentVariable_alreadyExists(t *testing.T) { environment = "%s" } `, repoName, envName), - Check: resource.ComposeTestCheckFunc( - func(s *terraform.State) error { - // Now that the repo and env are created, create the variable using the API. - client := testAccProvider.Meta().(*Owner).v3client - owner := testAccProvider.Meta().(*Owner).name - ctx := context.Background() - escapedEnvName := url.PathEscape(envName) - - variable := &github.ActionsVariable{ - Name: varName, - Value: value, - } - _, err := client.Actions.CreateEnvVariable(ctx, owner, repoName, escapedEnvName, variable) - return err - }, - ), - }, - { - // Now, run the full config. Terraform should detect the existing variable and "adopt" it. - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_actions_environment_variable.variable", "value", value), - ), - }, + Check: resource.ComposeTestCheckFunc( + func(s *terraform.State) error { + // Now that the repo and env are created, create the variable using the API. + client := testAccProvider.Meta().(*Owner).v3client + owner := testAccProvider.Meta().(*Owner).name + ctx := context.Background() + escapedEnvName := url.PathEscape(envName) + + variable := &github.ActionsVariable{ + Name: varName, + Value: value, + } + _, err := client.Actions.CreateEnvVariable(ctx, owner, repoName, escapedEnvName, variable) + return err + }, + ), }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + // Now, run the full config. Terraform should detect the existing variable and "adopt" it. + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_actions_environment_variable.variable", "value", value), + ), + }, + }, }) } diff --git a/github/resource_github_actions_hosted_runner_test.go b/github/resource_github_actions_hosted_runner_test.go index 29a2542959..a21e47c931 100644 --- a/github/resource_github_actions_hosted_runner_test.go +++ b/github/resource_github_actions_hosted_runner_test.go @@ -20,7 +20,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-%s" - + image { id = "2306" source = "github" @@ -74,29 +74,15 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for hosted runners") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -109,7 +95,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-optional-%s" - + image { id = "2306" source = "github" @@ -141,21 +127,15 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -168,7 +148,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-update-%s" - + image { id = "2306" source = "github" @@ -188,7 +168,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-update-%s-updated" - + image { id = "2306" source = "github" @@ -230,25 +210,19 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configBefore, - Check: checkBefore, - }, - { - Config: configAfter, - Check: checkAfter, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configBefore, + Check: checkBefore, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configAfter, + Check: checkAfter, + }, + }, }) }) @@ -261,7 +235,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-size-%s" - + image { id = "2306" source = "github" @@ -280,7 +254,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-size-%s" - + image { id = "2306" source = "github" @@ -313,25 +287,19 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configBefore, - Check: checkBefore, - }, - { - Config: configAfter, - Check: checkAfter, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configBefore, + Check: checkBefore, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configAfter, + Check: checkAfter, + }, + }, }) }) @@ -344,7 +312,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-import-%s" - + image { id = "2306" source = "github" @@ -365,27 +333,21 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_hosted_runner.test", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"image", "image_gen"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_hosted_runner.test", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"image", "image_gen"}, + }, + }, }) }) @@ -398,7 +360,7 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { resource "github_actions_hosted_runner" "test" { name = "tf-acc-test-delete-%s" - + image { id = "2306" source = "github" @@ -409,34 +371,28 @@ func TestAccGithubActionsHostedRunner(t *testing.T) { } `, randomID, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_actions_hosted_runner.test", "id", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet( + "github_actions_hosted_runner.test", "id", ), - }, - // This step should successfully delete the runner - { - Config: fmt.Sprintf(` + ), + }, + // This step should successfully delete the runner + { + Config: fmt.Sprintf(` resource "github_actions_runner_group" "test" { name = "tf-acc-test-group-%s" visibility = "all" } `, randomID), - }, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_organization_oidc_subject_claim_customization_template_test.go b/github/resource_github_actions_organization_oidc_subject_claim_customization_template_test.go index 7a07b06348..3fd221fa73 100644 --- a/github/resource_github_actions_organization_oidc_subject_claim_customization_template_test.go +++ b/github/resource_github_actions_organization_oidc_subject_claim_customization_template_test.go @@ -32,26 +32,15 @@ func TestAccGithubActionsOrganizationOIDCSubjectClaimCustomizationTemplate(t *te "include_claim_keys.2", "job_workflow_ref", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -111,33 +100,19 @@ func TestAccGithubActionsOrganizationOIDCSubjectClaimCustomizationTemplate(t *te ), ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) @@ -166,33 +141,20 @@ func TestAccGithubActionsOrganizationOIDCSubjectClaimCustomizationTemplate(t *te ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_organization_oidc_subject_claim_customization_template.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_organization_oidc_subject_claim_customization_template.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_actions_organization_permissions_test.go b/github/resource_github_actions_organization_permissions_test.go index 5f7bf2b20d..0197a83463 100644 --- a/github/resource_github_actions_organization_permissions_test.go +++ b/github/resource_github_actions_organization_permissions_test.go @@ -29,21 +29,15 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -90,26 +84,20 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_organization_permissions.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_organization_permissions.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -144,21 +132,15 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -186,21 +168,15 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -246,21 +222,15 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_organization_secret.go b/github/resource_github_actions_organization_secret.go index 9601ba5aab..7766ca2970 100644 --- a/github/resource_github_actions_organization_secret.go +++ b/github/resource_github_actions_organization_secret.go @@ -23,6 +23,9 @@ func resourceGithubActionsOrganizationSecret() *schema.Resource { if err := d.Set("secret_name", d.Id()); err != nil { return nil, err } + if err := d.Set("destroy_on_drift", true); err != nil { + return nil, err + } return []*schema.ResourceData{d}, nil }, }, diff --git a/github/resource_github_actions_organization_secret_repositories_test.go b/github/resource_github_actions_organization_secret_repositories_test.go index ab721a1abc..4adf359826 100644 --- a/github/resource_github_actions_organization_secret_repositories_test.go +++ b/github/resource_github_actions_organization_secret_repositories_test.go @@ -50,29 +50,15 @@ func TestAccGithubActionsOrganizationSecretRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_organization_secret_repository_test.go b/github/resource_github_actions_organization_secret_repository_test.go index 31d9e02cd5..ab6465feac 100644 --- a/github/resource_github_actions_organization_secret_repository_test.go +++ b/github/resource_github_actions_organization_secret_repository_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,13 +9,11 @@ import ( ) func TestAccGithubActionsOrganizationSecretRepository(t *testing.T) { - const ORG_SECRET_NAME = "ORG_SECRET_NAME" - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - secret_name, exists := os.LookupEnv(ORG_SECRET_NAME) - t.Run("set repository allowlist for a organization secret", func(t *testing.T) { - if !exists { - t.Skipf("%s environment variable is missing", ORG_SECRET_NAME) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + secretName := testAccConf.testOrgSecretName + if len(secretName) == 0 { + t.Skip("test organization secret name is not set") } config := fmt.Sprintf(` @@ -30,7 +27,7 @@ func TestAccGithubActionsOrganizationSecretRepository(t *testing.T) { secret_name = "%s" repository_id = github_repository.test_repo_1.repo_id } - `, randomID, secret_name) + `, randomID, secretName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -41,29 +38,15 @@ func TestAccGithubActionsOrganizationSecretRepository(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_organization_secret_test.go b/github/resource_github_actions_organization_secret_test.go index 1f213c5082..70ccaa5511 100644 --- a/github/resource_github_actions_organization_secret_test.go +++ b/github/resource_github_actions_organization_secret_test.go @@ -65,35 +65,21 @@ func TestAccGithubActionsOrganizationSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) @@ -110,29 +96,15 @@ func TestAccGithubActionsOrganizationSecret(t *testing.T) { } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -154,35 +126,21 @@ func TestAccGithubActionsOrganizationSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_organization_secret.test_secret", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"plaintext_value"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_organization_secret.test_secret", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"plaintext_value"}, + }, + }, }) }) diff --git a/github/resource_github_actions_organization_variable_test.go b/github/resource_github_actions_organization_variable_test.go index 0b8f6b7418..408cbe5db4 100644 --- a/github/resource_github_actions_organization_variable_test.go +++ b/github/resource_github_actions_organization_variable_test.go @@ -53,35 +53,21 @@ func TestAccGithubActionsOrganizationVariable(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - value, - updatedValue, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + value, + updatedValue, 1), + Check: checks["after"], + }, + }, }) }) @@ -125,29 +111,15 @@ func TestAccGithubActionsOrganizationVariable(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -160,29 +132,15 @@ func TestAccGithubActionsOrganizationVariable(t *testing.T) { } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -198,34 +156,20 @@ func TestAccGithubActionsOrganizationVariable(t *testing.T) { } `, varName, value) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - ResourceName: "github_actions_organization_variable.variable", - ImportStateId: varName, - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_organization_variable.variable", + ImportStateId: varName, + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_actions_repository_access_level_test.go b/github/resource_github_actions_repository_access_level_test.go index 795dc58aee..884c8c7d50 100644 --- a/github/resource_github_actions_repository_access_level_test.go +++ b/github/resource_github_actions_repository_access_level_test.go @@ -32,29 +32,15 @@ func TestAccGithubActionsRepositoryAccessLevel(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - t.Skip("organization account not supported for this input") + }, }) }) @@ -81,29 +67,15 @@ func TestAccGithubActionsRepositoryAccessLevel(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this input") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_repository_oidc_subject_claim_customization_template_test.go b/github/resource_github_actions_repository_oidc_subject_claim_customization_template_test.go index a4c507ec6d..3dc17e14c0 100644 --- a/github/resource_github_actions_repository_oidc_subject_claim_customization_template_test.go +++ b/github/resource_github_actions_repository_oidc_subject_claim_customization_template_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates repository oidc subject claim customization template without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -45,30 +44,20 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test "include_claim_keys.2", "job_workflow_ref", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("updates repository oidc subject claim customization template without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) configTemplate := ` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -160,41 +149,28 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test ), ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, - { - Config: configs["reset_to_default"], - Check: checks["reset_to_default"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + { + Config: configs["reset_to_default"], + Check: checks["reset_to_default"], + }, + }, }) }) t.Run("imports repository oidc subject claim customization template without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -229,33 +205,20 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_repository_oidc_subject_claim_customization_template.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_repository_oidc_subject_claim_customization_template.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_actions_repository_permissions_test.go b/github/resource_github_actions_repository_permissions_test.go index ab046661c8..9ab8191ca2 100644 --- a/github/resource_github_actions_repository_permissions_test.go +++ b/github/resource_github_actions_repository_permissions_test.go @@ -32,29 +32,15 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -91,34 +77,20 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_repository_permissions.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_repository_permissions.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -155,29 +127,15 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -209,29 +167,15 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -258,29 +202,15 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -315,29 +245,15 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_runner_group_test.go b/github/resource_github_actions_runner_group_test.go index 546392a4ad..170b7402fa 100644 --- a/github/resource_github_actions_runner_group_test.go +++ b/github/resource_github_actions_runner_group_test.go @@ -12,11 +12,8 @@ import ( ) func TestAccGithubActionsRunnerGroup(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates runner groups without error", func(t *testing.T) { - // t.Skip("requires an enterprise cloud account") - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -24,19 +21,9 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { auto_init = true } - resource "github_branch" "test" { - repository = github_repository.test.name - branch = "test" - } - - resource "github_branch_default" "default"{ - repository = github_repository.test.name - branch = github_branch.test.branch - } - resource "github_repository_file" "workflow_file" { - depends_on = [github_branch_default.default] repository = github_repository.test.name + branch = "main" file = ".github/workflows/test.yml" content = "" commit_message = "Managed by Terraform" @@ -47,11 +34,11 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { resource "github_actions_runner_group" "test" { depends_on = [github_repository_file.workflow_file] - + name = github_repository.test.name visibility = "all" restricted_to_workflows = true - selected_workflows = ["${github_repository.test.full_name}/.github/workflows/test.yml@refs/heads/${github_branch.test.branch}"] + selected_workflows = ["${github_repository.test.full_name}/.github/workflows/test.yml@refs/heads/main"] allows_public_repositories = true } `, randomID) @@ -83,7 +70,7 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { runnerGroup := state.RootModule().Resources["github_actions_runner_group.test"].Primary workflowActual := runnerGroup.Attributes["selected_workflows.0"] - workflowExpected := fmt.Sprintf("%s/.github/workflows/test.yml@refs/heads/test", fullName) + workflowExpected := fmt.Sprintf("%s/.github/workflows/test.yml@refs/heads/main", fullName) if workflowActual != workflowExpected { return fmt.Errorf("actual selected workflows %s not the same as expected selected workflows %s", @@ -97,35 +84,20 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("manages runner visibility", func(t *testing.T) { - // t.Skip("requires an enterprise cloud account") - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -159,33 +131,20 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports an all runner group without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -204,38 +163,30 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_runner_group.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_runner_group.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) t.Run("imports a private runner group without error", func(t *testing.T) { + // Note: this test is skipped because when setting visibility 'private', it always fails with: + // Step 0 error: After applying this step, the plan was not empty: + // visibility: "all" => "private" + t.Skip("This is not supported") + + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -253,42 +204,25 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "visibility"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_runner_group.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - // Note: this test is skipped because when setting visibility 'private', it always fails with: - // Step 0 error: After applying this step, the plan was not empty: - // visibility: "all" => "private" - t.Skip("always shows a diff for visibility 'all' => 'private'") - testCase(t, organization) + { + ResourceName: "github_actions_runner_group.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) t.Run("imports a selected runner group without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -312,30 +246,20 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_actions_runner_group.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_runner_group.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_actions_secret_test.go b/github/resource_github_actions_secret_test.go index 064d11bf04..82fb725e5c 100644 --- a/github/resource_github_actions_secret_test.go +++ b/github/resource_github_actions_secret_test.go @@ -12,11 +12,10 @@ import ( ) func TestAccGithubActionsSecret(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("reads a repository public key without error", func(t *testing.T) { - config := fmt.Sprintf(` + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" } @@ -24,7 +23,6 @@ func TestAccGithubActionsSecret(t *testing.T) { data "github_actions_public_key" "test_pk" { repository = github_repository.test.name } - `, randomID) check := resource.ComposeAggregateTestCheckFunc( @@ -36,33 +34,20 @@ func TestAccGithubActionsSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates and updates secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) @@ -119,39 +104,26 @@ func TestAccGithubActionsSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) t.Run("creates and updates repository name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) repoName := fmt.Sprintf("tf-acc-test-%s", randomID) updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) @@ -217,39 +189,26 @@ func TestAccGithubActionsSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - repoName, - updatedRepoName, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + repoName, + updatedRepoName, 2), + Check: checks["after"], + }, + }, }) }) t.Run("deletes secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -266,29 +225,15 @@ func TestAccGithubActionsSecret(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -322,42 +267,28 @@ func TestAccGithubActionsSecret(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_actions_secret.with_drift_true", "destroy_on_drift", "true"), - resource.TestCheckResourceAttr( - "github_actions_secret.with_drift_false", "destroy_on_drift", "false"), - resource.TestCheckResourceAttr( - "github_actions_secret.default_behavior", "destroy_on_drift", "true"), - resource.TestCheckResourceAttr( - "github_actions_secret.with_drift_true", "plaintext_value", "initial_value"), - resource.TestCheckResourceAttr( - "github_actions_secret.with_drift_false", "plaintext_value", "initial_value"), - resource.TestCheckResourceAttr( - "github_actions_secret.default_behavior", "plaintext_value", "initial_value"), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_actions_secret.with_drift_true", "destroy_on_drift", "true"), + resource.TestCheckResourceAttr( + "github_actions_secret.with_drift_false", "destroy_on_drift", "false"), + resource.TestCheckResourceAttr( + "github_actions_secret.default_behavior", "destroy_on_drift", "true"), + resource.TestCheckResourceAttr( + "github_actions_secret.with_drift_true", "plaintext_value", "initial_value"), + resource.TestCheckResourceAttr( + "github_actions_secret.with_drift_false", "plaintext_value", "initial_value"), + resource.TestCheckResourceAttr( + "github_actions_secret.default_behavior", "plaintext_value", "initial_value"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_actions_variable_test.go b/github/resource_github_actions_variable_test.go index 8f86308340..f5d7230b22 100644 --- a/github/resource_github_actions_variable_test.go +++ b/github/resource_github_actions_variable_test.go @@ -11,9 +11,8 @@ import ( ) func TestAccGithubActionsVariable(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates repository variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) value := "my_variable_value" updatedValue := "my_updated_variable_value" @@ -56,39 +55,26 @@ func TestAccGithubActionsVariable(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - value, - updatedValue, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + value, + updatedValue, 1), + Check: checks["after"], + }, + }, }) }) t.Run("deletes repository variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -101,33 +87,20 @@ func TestAccGithubActionsVariable(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports repository variables without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) varName := "test_variable" value := "variable_value" @@ -143,34 +116,20 @@ func TestAccGithubActionsVariable(t *testing.T) { } `, randomID, varName, value) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - ResourceName: "github_actions_variable.variable", - ImportStateId: fmt.Sprintf(`tf-acc-test-%s:%s`, randomID, varName), - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_actions_variable.variable", + ImportStateId: fmt.Sprintf(`tf-acc-test-%s:%s`, randomID, varName), + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_app_installation_repositories_test.go b/github/resource_github_app_installation_repositories_test.go index 6a12f5f9d8..80ff60342d 100644 --- a/github/resource_github_app_installation_repositories_test.go +++ b/github/resource_github_app_installation_repositories_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,35 +9,34 @@ import ( ) func TestAccGithubAppInstallationRepositories(t *testing.T) { - const APP_INSTALLATION_ID = "APP_INSTALLATION_ID" - randomID1 := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - randomID2 := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - installation_id, exists := os.LookupEnv(APP_INSTALLATION_ID) + t.Skip("TODO: Broken test") + if testAccConf.testOrgAppInstallationId == 0 { + t.Skip("No org app installation id provided") + } t.Run("installs an app to multiple repositories", func(t *testing.T) { - if !exists { - t.Skipf("%s environment variable is missing", APP_INSTALLATION_ID) - } + randomId := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName0 := fmt.Sprintf("tf-acc-test-0-%s", randomId) + repoName1 := fmt.Sprintf("tf-acc-test-1-%s", randomId) config := fmt.Sprintf(` - - resource "github_repository" "test1" { - name = "tf-acc-test-%s" + resource "github_repository" "test_0" { + name = "%s" auto_init = true } - resource "github_repository" "test2" { + resource "github_repository" "test_1" { name = "tf-acc-test-%s" auto_init = true } resource "github_app_installation_repositories" "test" { # The installation id of the app (in the organization). - installation_id = "%s" - selected_repositories = [github_repository.test1.name, github_repository.test2.name] + installation_id = "%d" + selected_repositories = [github_repository.test_0.name, github_repository.test_1.name] } - `, randomID1, randomID2, installation_id) + `, repoName0, repoName1, testAccConf.testOrgAppInstallationId) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -49,29 +47,15 @@ func TestAccGithubAppInstallationRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_app_installation_repository_test.go b/github/resource_github_app_installation_repository_test.go index cede5b5ecf..3c1f524f06 100644 --- a/github/resource_github_app_installation_repository_test.go +++ b/github/resource_github_app_installation_repository_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,15 +9,13 @@ import ( ) func TestAccGithubAppInstallationRepository(t *testing.T) { - const APP_INSTALLATION_ID = "APP_INSTALLATION_ID" - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - installation_id, exists := os.LookupEnv(APP_INSTALLATION_ID) + t.Skip("TODO: Broken test") + if testAccConf.testOrgAppInstallationId == 0 { + t.Skip("No org app installation id provided") + } t.Run("installs an app to a repository", func(t *testing.T) { - if !exists { - t.Skipf("%s environment variable is missing", APP_INSTALLATION_ID) - } - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -28,11 +25,11 @@ func TestAccGithubAppInstallationRepository(t *testing.T) { resource "github_app_installation_repository" "test" { # The installation id of the app (in the organization). - installation_id = "%s" + installation_id = "%d" repository = github_repository.test.name } - `, randomID, installation_id) + `, randomID, testAccConf.testOrgAppInstallationId) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -43,29 +40,15 @@ func TestAccGithubAppInstallationRepository(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_branch_default_test.go b/github/resource_github_branch_default_test.go index 371c65327e..1795ea267e 100644 --- a/github/resource_github_branch_default_test.go +++ b/github/resource_github_branch_default_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubBranchDefault(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and manages branch defaults", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -36,33 +35,20 @@ func TestAccGithubBranchDefault(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("replaces the default_branch of a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -88,35 +74,29 @@ func TestAccGithubBranchDefault(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: ` + removed { + from = github_branch.test + lifecycle { destroy = false } + } + `, + }, + }, }) }) t.Run("creates and manages branch defaults even if rename is set", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true @@ -140,33 +120,20 @@ func TestAccGithubBranchDefault(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("replaces the default_branch of a repository without creating a branch resource prior to", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -178,39 +145,17 @@ func TestAccGithubBranchDefault(t *testing.T) { branch = "development" rename = true } - `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_branch_default.test", "branch", - "development", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc(resource.TestCheckResourceAttr("github_branch_default.test", "branch", "development")), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_branch_protection_test.go b/github/resource_github_branch_protection_test.go index 818a16e1f7..4a03630305 100644 --- a/github/resource_github_branch_protection_test.go +++ b/github/resource_github_branch_protection_test.go @@ -56,47 +56,33 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importBranchProtectionByRepoName( - fmt.Sprintf("tf-acc-test-%s", randomID), "main", - ), - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ExpectError: regexp.MustCompile( - `could not find a branch protection rule with the pattern 'no-such-pattern'`, - ), - ImportStateIdFunc: importBranchProtectionByRepoName( - fmt.Sprintf("tf-acc-test-%s", randomID), "no-such-pattern", - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importBranchProtectionByRepoName( + fmt.Sprintf("tf-acc-test-%s", randomID), "main", + ), + }, + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ExpectError: regexp.MustCompile( + `could not find a branch protection rule with the pattern 'no-such-pattern'`, + ), + ImportStateIdFunc: importBranchProtectionByRepoName( + fmt.Sprintf("tf-acc-test-%s", randomID), "no-such-pattern", + ), + }, + }, }) }) @@ -147,47 +133,33 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importBranchProtectionByRepoName( - fmt.Sprintf("tf-acc-test-%s", randomID), "main", - ), - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ExpectError: regexp.MustCompile( - `could not find a branch protection rule with the pattern 'no-such-pattern'`, - ), - ImportStateIdFunc: importBranchProtectionByRepoName( - fmt.Sprintf("tf-acc-test-%s", randomID), "no-such-pattern", - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importBranchProtectionByRepoName( + fmt.Sprintf("tf-acc-test-%s", randomID), "main", + ), + }, + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ExpectError: regexp.MustCompile( + `could not find a branch protection rule with the pattern 'no-such-pattern'`, + ), + ImportStateIdFunc: importBranchProtectionByRepoName( + fmt.Sprintf("tf-acc-test-%s", randomID), "no-such-pattern", + ), + }, + }, }) }) @@ -221,45 +193,31 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importBranchProtectionByRepoID( - "github_repository.test", "main"), - }, - { - ResourceName: "github_branch_protection.test", - ImportState: true, - ExpectError: regexp.MustCompile( - `could not find a branch protection rule with the pattern 'no-such-pattern'`, - ), - ImportStateIdFunc: importBranchProtectionByRepoID( - "github_repository.test", "no-such-pattern"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importBranchProtectionByRepoID( + "github_repository.test", "main"), + }, + { + ResourceName: "github_branch_protection.test", + ImportState: true, + ExpectError: regexp.MustCompile( + `could not find a branch protection rule with the pattern 'no-such-pattern'`, + ), + ImportStateIdFunc: importBranchProtectionByRepoID( + "github_repository.test", "no-such-pattern"), + }, + }, }) }) @@ -306,29 +264,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -362,29 +306,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -412,7 +342,7 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ] } } - `, randomID, testOwnerFunc()) + `, randomID, testAccConf.username) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -426,36 +356,21 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("configures branch push restrictions with username", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - user := fmt.Sprintf("/%s", testOwnerFunc()) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -469,11 +384,11 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { restrict_pushes { push_allowances = [ - "%s", + "/%s", ] } } - `, randomID, user) + `, randomID, testAccConf.username) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -487,29 +402,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -545,29 +446,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -593,7 +480,7 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { allows_force_pushes = true } - `, randomID, testOwnerFunc()) + `, randomID, testAccConf.username) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -604,29 +491,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -655,7 +528,7 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { } - `, randomID, testOwnerFunc()) + `, randomID, testAccConf.username) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -663,29 +536,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -718,7 +577,7 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ] } - `, randomID, randomID, testOrganization) + `, randomID, randomID, testAccConf.owner) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -729,22 +588,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - // This test only works with an organization account - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -775,36 +627,21 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("configures non-empty list of pull request bypassers", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - user := fmt.Sprintf("/%s", testOwnerFunc()) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -819,13 +656,13 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { required_pull_request_reviews { pull_request_bypassers = [ - "%s", + "/%s", ] } } - `, randomID, user) + `, randomID, testAccConf.username) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -833,29 +670,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -888,29 +711,15 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_branch_protection_v3_test.go b/github/resource_github_branch_protection_v3_test.go index 0725e86f49..8e892fb667 100644 --- a/github/resource_github_branch_protection_v3_test.go +++ b/github/resource_github_branch_protection_v3_test.go @@ -8,282 +8,487 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccGithubBranchProtectionV3_defaults(t *testing.T) { +func TestAccGithubBranchProtectionV3_required_pull_request_reviews(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("configures default settings when empty", func(t *testing.T) { + t.Run("configures required pull request reviews", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } - resource "github_branch_protection_v3" "test" { + resource "github_team" "test" { + name = "tf-acc-test-%[1]s" + } - repository = github_repository.test.name - branch = "main" + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "admin" + } - } + resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" + + required_pull_request_reviews { + dismiss_stale_reviews = true + require_code_owner_reviews = true + required_approving_review_count = 1 + require_last_push_approval = true + dismissal_users = ["a"] + dismissal_teams = ["b"] + dismissal_apps = ["c"] + bypass_pull_request_allowances { + users = ["d"] + teams = [github_team.test.slug] + apps = ["e"] + } + } + + depends_on = [github_team_repository.test] + } `, randomID) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "branch", "main", + "github_branch_protection_v3.test", "required_pull_request_reviews.#", "1", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "require_signed_commits", "false", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.dismiss_stale_reviews", "true", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "require_conversation_resolution", "false", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.require_code_owner_reviews", "true", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.#", "0", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.required_approving_review_count", "1", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_pull_request_reviews.#", "0", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.require_last_push_approval", "true", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "push_restrictions.#", "0", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.dismissal_users.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.dismissal_teams.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.dismissal_apps.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.bypass_pull_request_allowances.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.bypass_pull_request_allowances.0.users.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.bypass_pull_request_allowances.0.teams.#", "1", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_pull_request_reviews.0.bypass_pull_request_allowances.0.apps.#", "1", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } -func TestAccGithubBranchProtectionV3_conversation_resolution(t *testing.T) { +func TestAccGithubBranchProtectionV3RequiredPullRequestReviewsBypassAllowances(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("configures default settings when empty", func(t *testing.T) { + t.Run("configures required pull request reviews with bypass allowances", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } - resource "github_branch_protection_v3" "test" { + resource "github_team" "test" { + name = "tf-acc-test-%[1]s" + } - repository = github_repository.test.name - branch = "main" + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "admin" + } - require_conversation_resolution = true - } + resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" + + required_pull_request_reviews { + bypass_pull_request_allowances { + teams = [github_team.test.slug] + } + } + + depends_on = [github_team_repository.test] + } `, randomID) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "branch", "main", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "require_signed_commits", "false", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "require_conversation_resolution", "true", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.#", "0", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_pull_request_reviews.#", "0", + "github_branch_protection_v3.test", "required_pull_request_reviews.#", "1", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "push_restrictions.#", "0", + "github_branch_protection_v3.test", "required_pull_request_reviews.0.bypass_pull_request_allowances.#", "1", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } -func TestAccGithubBranchProtectionV3_required_status_checks(t *testing.T) { +func TestAccGithubBranchProtectionV3_branch_push_restrictions(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("configures required status checks", func(t *testing.T) { + t.Run("configures branch push restrictions", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } + resource "github_team" "test" { + name = "tf-acc-test-%[1]s" + } + + resource "github_team_repository" "test" { + team_id = "${github_team.test.id}" + repository = "${github_repository.test.name}" + permission = "pull" + } + resource "github_branch_protection_v3" "test" { - repository = github_repository.test.name - branch = "main" + repository = github_repository.test.name + branch = "main" - required_status_checks { - strict = true - checks = [ - "github/foo", - "github/bar:-1", - "github:foo:baz:1", - ] + restrictions { + teams = ["${github_team.test.slug}"] } } - - `, randomID) + `, randomID) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.#", "1", + "github_branch_protection_v3.test", "restrictions.#", "1", ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) +} + +func TestAccGithubBranchProtectionV3_computed_status_checks_no_churn(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + + t.Run("handles computed status checks without churn", func(t *testing.T) { + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" + + required_status_checks { + strict = true + checks = [ + "ci/test", + "ci/build" + ] + } + } + `, randomID) + + check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.strict", "true", + "github_branch_protection_v3.test", "required_status_checks.#", "1", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.checks.#", "3", + "github_branch_protection_v3.test", "required_status_checks.0.strict", "true", ), resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.checks.0", "github/foo", + "github_branch_protection_v3.test", "required_status_checks.0.checks.#", "2", ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.checks.1", "github/bar", + resource.TestCheckTypeSetElemAttr( + "github_branch_protection_v3.test", "required_status_checks.0.checks.*", "ci/test", ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.checks.2", "github:foo:baz", + resource.TestCheckTypeSetElemAttr( + "github_branch_protection_v3.test", "required_status_checks.0.checks.*", "ci/build", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + // Re-apply the same config to test for churn + { + Config: config, + Check: check, + PlanOnly: true, + }, + }, }) }) } -func TestAccGithubBranchProtectionV3_required_status_contexts(t *testing.T) { +func TestAccGithubBranchProtectionV3_computed_status_contexts_no_churn(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("configures required status checks", func(t *testing.T) { + t.Run("handles computed status contexts without churn", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true + name = "tf-acc-test-%s" + auto_init = true } resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" - repository = github_repository.test.name - branch = "main" - - required_status_checks { - strict = true - contexts = ["github/foo"] - } - + required_status_checks { + strict = true + contexts = [ + "ci/test", + "ci/build" + ] + } } - - `, randomID) + `, randomID) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( "github_branch_protection_v3.test", "required_status_checks.#", "1", ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_status_checks.0.strict", "true", + ), + resource.TestCheckResourceAttr( + "github_branch_protection_v3.test", "required_status_checks.0.contexts.#", "2", + ), + resource.TestCheckTypeSetElemAttr( + "github_branch_protection_v3.test", "required_status_checks.0.contexts.*", "ci/test", + ), + resource.TestCheckTypeSetElemAttr( + "github_branch_protection_v3.test", "required_status_checks.0.contexts.*", "ci/build", + ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + // Re-apply the same config to test for churn + { + Config: config, + Check: check, + PlanOnly: true, }, - }) + }, + }) + }) +} + +func TestAccGithubBranchProtectionV3(t *testing.T) { + t.Run("configures default settings when empty", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_branch_protection_v3" "test" { + + repository = github_repository.test.name + branch = "main" + } + `, randomID) - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "branch", "main"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "require_signed_commits", "false"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "require_conversation_resolution", "false"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.#", "0"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_pull_request_reviews.#", "0"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "push_restrictions.#", "0"), + ), + }, + }, }) + }) + + t.Run("configures conversation resolution", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_branch_protection_v3" "test" { + + repository = github_repository.test.name + branch = "main" + + require_conversation_resolution = true + } + `, randomID) - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "branch", "main"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "require_signed_commits", "false"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "require_conversation_resolution", "true"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.#", "0"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_pull_request_reviews.#", "0"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "push_restrictions.#", "0"), + ), + }, + }, }) + }) + + t.Run("configures required status checks", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" + + required_status_checks { + strict = true + checks = [ + "github/foo", + "github/bar:-1", + "github:foo:baz:1", + ] + } + + } + `, randomID) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("github_branch_protection_v3.test", "required_status_checks.#"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.#", "1"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.0.strict", "true"), + resource.TestCheckResourceAttrSet("github_branch_protection_v3.test", "required_status_checks.0.checks.#"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.0.checks.#", "3"), + ), + }, + }, }) }) -} -func TestAccGithubBranchProtectionV3_required_pull_request_reviews(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + t.Run("configures required status checks context", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_branch_protection_v3" "test" { + repository = github_repository.test.name + branch = "main" + + required_status_checks { + strict = true + contexts = ["github/foo"] + } + } + `, randomID) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeAggregateTestCheckFunc( + resource.TestCheckResourceAttrSet("github_branch_protection_v3.test", "required_status_checks.#"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.#", "1"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.0.strict", "true"), + resource.TestCheckResourceAttrSet("github_branch_protection_v3.test", "required_status_checks.0.checks.#"), + resource.TestCheckResourceAttr("github_branch_protection_v3.test", "required_status_checks.0.checks.#", "1"), + ), + }, + }, + }) + }) t.Run("configures required pull request reviews", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -364,37 +569,20 @@ func TestAccGithubBranchProtectionV3_required_pull_request_reviews(t *testing.T) ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubBranchProtectionV3RequiredPullRequestReviewsBypassAllowances(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("configures required pull request reviews with bypass allowances", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -436,37 +624,20 @@ func TestAccGithubBranchProtectionV3RequiredPullRequestReviewsBypassAllowances(t ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubBranchProtectionV3_branch_push_restrictions(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("configures branch push restrictions", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -501,179 +672,15 @@ func TestAccGithubBranchProtectionV3_branch_push_restrictions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) -} - -func TestAccGithubBranchProtectionV3_computed_status_checks_no_churn(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("handles computed status checks without churn", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } - - resource "github_branch_protection_v3" "test" { - repository = github_repository.test.name - branch = "main" - - required_status_checks { - strict = true - checks = [ - "ci/test", - "ci/build" - ] - } - } - `, randomID) - - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.#", "1", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.0.strict", "true", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.0.checks.#", "2", - ), - resource.TestCheckTypeSetElemAttr( - "github_branch_protection_v3.test", "required_status_checks.0.checks.*", "ci/test", - ), - resource.TestCheckTypeSetElemAttr( - "github_branch_protection_v3.test", "required_status_checks.0.checks.*", "ci/build", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - // Re-apply the same config to test for churn - { - Config: config, - Check: check, - PlanOnly: true, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) -} - -func TestAccGithubBranchProtectionV3_computed_status_contexts_no_churn(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("handles computed status contexts without churn", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" - auto_init = true - } - - resource "github_branch_protection_v3" "test" { - repository = github_repository.test.name - branch = "main" - - required_status_checks { - strict = true - contexts = [ - "ci/test", - "ci/build" - ] - } - } - `, randomID) - - check := resource.ComposeAggregateTestCheckFunc( - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.#", "1", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.0.strict", "true", - ), - resource.TestCheckResourceAttr( - "github_branch_protection_v3.test", "required_status_checks.0.contexts.#", "2", - ), - resource.TestCheckTypeSetElemAttr( - "github_branch_protection_v3.test", "required_status_checks.0.contexts.*", "ci/test", - ), - resource.TestCheckTypeSetElemAttr( - "github_branch_protection_v3.test", "required_status_checks.0.contexts.*", "ci/build", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - // Re-apply the same config to test for churn - { - Config: config, - Check: check, - PlanOnly: true, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_branch_test.go b/github/resource_github_branch_test.go index 7de895f1cb..9a2cbe89fa 100644 --- a/github/resource_github_branch_test.go +++ b/github/resource_github_branch_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,199 +9,113 @@ import ( ) func TestAccGithubBranch(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates a branch directly", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - } + resource "github_repository" "test" { + name = "tf-acc-test-%[1]s" + auto_init = true + } - resource "github_branch" "test" { - repository = github_repository.test.id - branch = "test" - } + resource "github_branch" "test" { + repository = github_repository.test.name + branch = "test" + } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "github_branch.test", "id", - regexp.MustCompile(fmt.Sprintf("tf-acc-test-%s:test", randomID)), - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:test", randomID), - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"source_sha"}, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:nonsense", randomID), - ExpectError: regexp.MustCompile( - "Repository tf-acc-test-[a-z0-9]* does not have a branch named nonsense.", - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_branch.test", "id"), + resource.TestCheckResourceAttr("github_branch.test", "ref", "refs/heads/test"), + resource.TestCheckResourceAttrSet("github_branch.test", "sha"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("creates a branch named main directly and a repository with a gitignore_template", func(t *testing.T) { + t.Run("creates a branch named main directly and a repository with a gitignore template", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - gitignore_template = "Python" - } + resource "github_repository" "test" { + name = "tf-acc-test-%[1]s" + auto_init = true + gitignore_template = "Python" + } - resource "github_branch" "test" { - repository = github_repository.test.id - branch = "main" - } + resource "github_branch" "test" { + repository = github_repository.test.id + branch = "main" + } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "github_branch.test", "id", - regexp.MustCompile(fmt.Sprintf("tf-acc-test-%s:test", randomID)), - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:test", randomID), - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"source_sha"}, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:nonsense", randomID), - ExpectError: regexp.MustCompile( - "Repository tf-acc-test-[a-z0-9]* does not have a branch named nonsense.", - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_branch.test", "id"), + resource.TestCheckResourceAttr("github_branch.test", "ref", "refs/heads/main"), + resource.TestCheckResourceAttrSet("github_branch.test", "sha"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: ` + removed { + from = github_branch.test + lifecycle { destroy = false } + } + `, + }, + }, }) }) t.Run("creates a branch from a source branch", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - } + resource "github_repository" "test" { + name = "tf-acc-test-%[1]s" + auto_init = true + } - resource "github_branch" "source" { - repository = github_repository.test.id - branch = "source" - } + resource "github_branch" "source" { + repository = github_repository.test.id + branch = "source" + } - resource "github_branch" "test" { - repository = github_repository.test.id - source_branch = github_branch.source.branch - branch = "test" - } + resource "github_branch" "test" { + repository = github_repository.test.id + source_branch = github_branch.source.branch + branch = "test" + } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestMatchResourceAttr( - "github_branch.test", "id", - regexp.MustCompile(fmt.Sprintf("tf-acc-test-%s:test", randomID)), - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:test:source", randomID), - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"source_sha"}, - }, - { - ResourceName: "github_branch.test", - ImportState: true, - ImportStateId: fmt.Sprintf("tf-acc-test-%s:nonsense:source", randomID), - ExpectError: regexp.MustCompile( - "Repository tf-acc-test-[a-z0-9]* does not have a branch named nonsense.", - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_branch.test", "id"), + resource.TestCheckResourceAttr("github_branch.test", "ref", "refs/heads/test"), + resource.TestCheckResourceAttrPair("github_branch.test", "sha", "github_branch.source", "sha"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("renames a branch without replacement", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) initialConfig := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%[1]s" @@ -227,36 +140,22 @@ func TestAccGithubBranch(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: initialConfig, - }, - { - Config: renamedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_branch.test", "branch", "renamed", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: initialConfig, + }, + { + Config: renamedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_branch.test", "branch", "renamed", ), - }, + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_codespaces_organization_secret_repositories_test.go b/github/resource_github_codespaces_organization_secret_repositories_test.go index 0c373f922e..653d58e820 100644 --- a/github/resource_github_codespaces_organization_secret_repositories_test.go +++ b/github/resource_github_codespaces_organization_secret_repositories_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,67 +9,46 @@ import ( ) func TestAccGithubCodespacesOrganizationSecretRepositories(t *testing.T) { - const ORG_SECRET_NAME = "ORG_SECRET_NAME" - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - secret_name, exists := os.LookupEnv(ORG_SECRET_NAME) - t.Run("set repository allowlist for an organization secret", func(t *testing.T) { - if !exists { - t.Skipf("%s environment variable is missing", ORG_SECRET_NAME) - } - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` + resource "github_actions_organization_secret" "test" { + secret_name = "TEST" + plaintext_value = "Testing 1..2..3.." + visibility = "all" + } + resource "github_repository" "test_repo_1" { name = "tf-acc-test-%s-1" - visibility = "internal" + visibility = "private" } resource "github_repository" "test_repo_2" { name = "tf-acc-test-%s-2" - visibility = "internal" + visibility = "private" } resource "github_codespaces_organization_secret_repositories" "org_secret_repos" { - secret_name = "%s" + secret_name = github_actions_organization_secret.test.secret_name selected_repository_ids = [ github_repository.test_repo_1.repo_id, github_repository.test_repo_2.repo_id ] } - `, randomID, randomID, secret_name) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_codespaces_organization_secret_repositories.org_secret_repos", "secret_name", - ), - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret_repositories.org_secret_repos", "selected_repository_ids.#", "2", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + `, randomID, randomID) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_codespaces_organization_secret_repositories.org_secret_repos", "secret_name"), + resource.TestCheckResourceAttr("github_codespaces_organization_secret_repositories.org_secret_repos", "selected_repository_ids.#", "2"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_codespaces_organization_secret_test.go b/github/resource_github_codespaces_organization_secret_test.go index 597695dcc1..6c71f046cb 100644 --- a/github/resource_github_codespaces_organization_secret_test.go +++ b/github/resource_github_codespaces_organization_secret_test.go @@ -3,7 +3,6 @@ package github import ( "encoding/base64" "fmt" - "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -12,125 +11,84 @@ import ( func TestAccGithubCodespacesOrganizationSecret(t *testing.T) { t.Run("creates and updates secrets without error", func(t *testing.T) { secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) - updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) + secretValueUpdated := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) config := fmt.Sprintf(` resource "github_codespaces_organization_secret" "plaintext_secret" { secret_name = "test_plaintext_secret" - plaintext_value = "%s" + plaintext_value = "%[1]s" visibility = "private" } resource "github_codespaces_organization_secret" "encrypted_secret" { secret_name = "test_encrypted_secret" - encrypted_value = "%s" + encrypted_value = "%[1]s" visibility = "private" } - `, secretValue, secretValue) + `, secretValue) - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret.plaintext_secret", "plaintext_value", - secretValue, - ), - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret.encrypted_secret", "encrypted_value", - secretValue, - ), - resource.TestCheckResourceAttrSet( - "github_codespaces_organization_secret.plaintext_secret", "created_at", - ), - resource.TestCheckResourceAttrSet( - "github_codespaces_organization_secret.plaintext_secret", "updated_at", - ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret.plaintext_secret", "plaintext_value", - updatedSecretValue, - ), - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret.encrypted_secret", "encrypted_value", - updatedSecretValue, - ), - resource.TestCheckResourceAttrSet( - "github_codespaces_organization_secret.plaintext_secret", "created_at", - ), - resource.TestCheckResourceAttrSet( - "github_codespaces_organization_secret.plaintext_secret", "updated_at", - ), - ), - } + configUpdated := fmt.Sprintf(` + resource "github_codespaces_organization_secret" "plaintext_secret" { + secret_name = "test_plaintext_secret" + plaintext_value = "%[1]s" + visibility = "private" + } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource "github_codespaces_organization_secret" "encrypted_secret" { + secret_name = "test_encrypted_secret" + encrypted_value = "%[1]s" + visibility = "private" + } + `, secretValueUpdated) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_codespaces_organization_secret.plaintext_secret", "plaintext_value", secretValue), + resource.TestCheckResourceAttr("github_codespaces_organization_secret.encrypted_secret", "encrypted_value", secretValue), + resource.TestCheckResourceAttrSet("github_codespaces_organization_secret.plaintext_secret", "created_at"), + resource.TestCheckResourceAttrSet("github_codespaces_organization_secret.plaintext_secret", "updated_at"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_codespaces_organization_secret.plaintext_secret", "plaintext_value", secretValueUpdated), + resource.TestCheckResourceAttr("github_codespaces_organization_secret.encrypted_secret", "encrypted_value", secretValueUpdated), + resource.TestCheckResourceAttrSet("github_codespaces_organization_secret.plaintext_secret", "created_at"), + resource.TestCheckResourceAttrSet("github_codespaces_organization_secret.plaintext_secret", "updated_at"), + ), + }, + }, }) }) t.Run("deletes secrets without error", func(t *testing.T) { config := ` - resource "github_codespaces_organization_secret" "plaintext_secret" { - secret_name = "test_plaintext_secret" - visibility = "private" - } - - resource "github_codespaces_organization_secret" "encrypted_secret" { - secret_name = "test_encrypted_secret" - visibility = "private" - } - ` - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, - }, - }) + resource "github_codespaces_organization_secret" "plaintext_secret" { + secret_name = "test_plaintext_secret" + visibility = "private" } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource "github_codespaces_organization_secret" "encrypted_secret" { + secret_name = "test_encrypted_secret" + visibility = "private" + } + ` + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, + }, + }, }) }) @@ -138,49 +96,24 @@ func TestAccGithubCodespacesOrganizationSecret(t *testing.T) { secretValue := "super_secret_value" config := fmt.Sprintf(` - resource "github_codespaces_organization_secret" "test_secret" { - secret_name = "test_plaintext_secret" - plaintext_value = "%s" - visibility = "private" - } + resource "github_codespaces_organization_secret" "test_secret" { + secret_name = "test_plaintext_secret" + plaintext_value = "%s" + visibility = "private" + } `, secretValue) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_codespaces_organization_secret.test_secret", "plaintext_value", - secretValue, - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_codespaces_organization_secret.test_secret", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"plaintext_value"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_codespaces_organization_secret.test_secret", "plaintext_value", secretValue), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_codespaces_secret_test.go b/github/resource_github_codespaces_secret_test.go index 8d7606e32d..54ae4c2c29 100644 --- a/github/resource_github_codespaces_secret_test.go +++ b/github/resource_github_codespaces_secret_test.go @@ -12,9 +12,8 @@ import ( ) func TestAccGithubCodespacesSecret(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("reads a repository public key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -36,33 +35,20 @@ func TestAccGithubCodespacesSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates and updates secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) @@ -119,39 +105,26 @@ func TestAccGithubCodespacesSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) t.Run("creates and updates repository name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) repoName := fmt.Sprintf("tf-acc-test-%s", randomID) updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) @@ -215,39 +188,26 @@ func TestAccGithubCodespacesSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - repoName, - updatedRepoName, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + repoName, + updatedRepoName, 2), + Check: checks["after"], + }, + }, }) }) t.Run("deletes secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -264,29 +224,15 @@ func TestAccGithubCodespacesSecret(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_codespaces_user_secret_test.go b/github/resource_github_codespaces_user_secret_test.go index befae37e06..aae9a4b0cc 100644 --- a/github/resource_github_codespaces_user_secret_test.go +++ b/github/resource_github_codespaces_user_secret_test.go @@ -61,31 +61,21 @@ func TestAccGithubCodespacesUserSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) @@ -100,25 +90,15 @@ func TestAccGithubCodespacesUserSecret(t *testing.T) { } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + }, }) }) @@ -139,31 +119,21 @@ func TestAccGithubCodespacesUserSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_codespaces_user_secret.test_secret", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"plaintext_value"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, individual) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + { + ResourceName: "github_codespaces_user_secret.test_secret", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"plaintext_value"}, + }, + }, }) }) } diff --git a/github/resource_github_dependabot_organization_secret_repositories_test.go b/github/resource_github_dependabot_organization_secret_repositories_test.go index 80c2ab09a3..bd62f0fa80 100644 --- a/github/resource_github_dependabot_organization_secret_repositories_test.go +++ b/github/resource_github_dependabot_organization_secret_repositories_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,69 +9,48 @@ import ( ) func TestAccGithubDependabotOrganizationSecretRepositories(t *testing.T) { - const ORG_SECRET_NAME = "ORG_SECRET_NAME" - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - secret_name, exists := os.LookupEnv(ORG_SECRET_NAME) - t.Run("set repository allowlist for an organization secret", func(t *testing.T) { - if !exists { - t.Skipf("%s environment variable is missing", ORG_SECRET_NAME) - } - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test_repo_1" { - name = "tf-acc-test-%s-1" - visibility = "internal" - vulnerability_alerts = "true" - } - - resource "github_repository" "test_repo_2" { - name = "tf-acc-test-%s-2" - visibility = "internal" - vulnerability_alerts = "true" - } - - resource "github_dependabot_organization_secret_repositories" "org_secret_repos" { - secret_name = "%s" - selected_repository_ids = [ - github_repository.test_repo_1.repo_id, - github_repository.test_repo_2.repo_id - ] - } - `, randomID, randomID, secret_name) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_dependabot_organization_secret_repositories.org_secret_repos", "secret_name", - ), - resource.TestCheckResourceAttr( - "github_dependabot_organization_secret_repositories.org_secret_repos", "selected_repository_ids.#", "2", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) + resource "github_actions_organization_secret" "test" { + secret_name = "TEST" + plaintext_value = "Testing 1..2..3.." + visibility = "all" } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + resource "github_repository" "test_repo_1" { + name = "tf-acc-test-%s-1" + visibility = "private" + vulnerability_alerts = "true" + } - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) + resource "github_repository" "test_repo_2" { + name = "tf-acc-test-%s-2" + visibility = "private" + vulnerability_alerts = "true" + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource "github_dependabot_organization_secret_repositories" "org_secret_repos" { + secret_name = github_actions_organization_secret.test.secret_name + selected_repository_ids = [ + github_repository.test_repo_1.repo_id, + github_repository.test_repo_2.repo_id + ] + } + `, randomID, randomID) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_dependabot_organization_secret_repositories.org_secret_repos", "secret_name"), + resource.TestCheckResourceAttr("github_dependabot_organization_secret_repositories.org_secret_repos", "selected_repository_ids.#", "2"), + ), + }, + }, }) }) } diff --git a/github/resource_github_dependabot_organization_secret_test.go b/github/resource_github_dependabot_organization_secret_test.go index 50a3a5a81b..90925c52f1 100644 --- a/github/resource_github_dependabot_organization_secret_test.go +++ b/github/resource_github_dependabot_organization_secret_test.go @@ -63,35 +63,21 @@ func TestAccGithubDependabotOrganizationSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) @@ -108,29 +94,15 @@ func TestAccGithubDependabotOrganizationSecret(t *testing.T) { } ` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -152,35 +124,21 @@ func TestAccGithubDependabotOrganizationSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_dependabot_organization_secret.test_secret", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"plaintext_value"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_dependabot_organization_secret.test_secret", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"plaintext_value"}, + }, + }, }) }) } diff --git a/github/resource_github_dependabot_secret_test.go b/github/resource_github_dependabot_secret_test.go index 8c53d4cecb..fe5b69c921 100644 --- a/github/resource_github_dependabot_secret_test.go +++ b/github/resource_github_dependabot_secret_test.go @@ -12,9 +12,8 @@ import ( ) func TestAccGithubDependabotSecret(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("reads a repository public key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -36,33 +35,20 @@ func TestAccGithubDependabotSecret(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates and updates secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) @@ -119,39 +105,26 @@ func TestAccGithubDependabotSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - secretValue, - updatedSecretValue, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + secretValue, + updatedSecretValue, 2), + Check: checks["after"], + }, + }, }) }) t.Run("creates and updates repository name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) repoName := fmt.Sprintf("tf-acc-test-%s", randomID) updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) @@ -217,39 +190,26 @@ func TestAccGithubDependabotSecret(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - repoName, - updatedRepoName, 2), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + repoName, + updatedRepoName, 2), + Check: checks["after"], + }, + }, }) }) t.Run("deletes secrets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -266,29 +226,15 @@ func TestAccGithubDependabotSecret(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_enterprise_actions_permissions_test.go b/github/resource_github_enterprise_actions_permissions_test.go index d3370f1856..1baa99175e 100644 --- a/github/resource_github_enterprise_actions_permissions_test.go +++ b/github/resource_github_enterprise_actions_permissions_test.go @@ -19,7 +19,7 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { allowed_actions = "%s" enabled_organizations = "%s" } - `, testEnterprise, allowedActions, enabledOrganizations) + `, testAccConf.enterpriseSlug, allowedActions, enabledOrganizations) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -30,27 +30,15 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -70,7 +58,7 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { data "github_user" "current" { username = "" } - + resource "github_enterprise_organization" "org" { enterprise_slug = "%s" name = "%s" @@ -95,7 +83,7 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { organization_ids = [github_enterprise_organization.org.id] } } - `, testEnterprise, orgName, displayName, desc, testEnterprise, allowedActions, enabledOrganizations, githubOwnedAllowed, verifiedAllowed) + `, testAccConf.enterpriseSlug, orgName, displayName, desc, testAccConf.enterpriseSlug, allowedActions, enabledOrganizations, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -112,32 +100,20 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_actions_permissions.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_actions_permissions.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -158,7 +134,7 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { verified_allowed = %t } } - `, testEnterprise, allowedActions, enabledOrganizations, githubOwnedAllowed, verifiedAllowed) + `, testAccConf.enterpriseSlug, allowedActions, enabledOrganizations, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -172,27 +148,15 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -242,7 +206,7 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { organization_ids = [github_enterprise_organization.org.id, github_enterprise_organization.org2.id] } } - `, testEnterprise, orgName, displayName, desc, testEnterprise, orgName2, displayName2, desc2, testEnterprise, allowedActions, enabledOrganizations) + `, testAccConf.enterpriseSlug, orgName, displayName, desc, testAccConf.enterpriseSlug, orgName2, displayName2, desc2, testAccConf.enterpriseSlug, allowedActions, enabledOrganizations) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -256,27 +220,15 @@ func TestAccGithubActionsEnterprisePermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) } diff --git a/github/resource_github_enterprise_actions_runner_group_test.go b/github/resource_github_enterprise_actions_runner_group_test.go index 6c6ed4264b..3695b870d1 100644 --- a/github/resource_github_enterprise_actions_runner_group_test.go +++ b/github/resource_github_enterprise_actions_runner_group_test.go @@ -10,17 +10,8 @@ import ( ) func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - t.Run("creates enterprise runner groups without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_enterprise" "enterprise" { slug = "%s" @@ -32,7 +23,7 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { visibility = "all" allows_public_repositories = true } - `, testEnterprise, randomID) + `, testAccConf.enterpriseSlug, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -52,25 +43,20 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) t.Run("manages runner group visibility to selected orgs", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_enterprise" "enterprise" { slug = "%s" @@ -86,7 +72,7 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { visibility = "selected" selected_organization_ids = [data.github_organization.org.id] } - `, testEnterprise, testOrganization, randomID) + `, testAccConf.enterpriseSlug, testAccConf.owner, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -109,25 +95,20 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) t.Run("imports an all runner group without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_enterprise" "enterprise" { slug = "%s" @@ -138,7 +119,7 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { name = "tf-acc-test-%s" visibility = "all" } - `, testEnterprise, randomID) + `, testAccConf.enterpriseSlug, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_enterprise_actions_runner_group.test", "name"), @@ -147,31 +128,26 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { resource.TestCheckResourceAttr("github_enterprise_actions_runner_group.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_actions_runner_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf(`%s/`, testEnterprise), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + { + ResourceName: "github_enterprise_actions_runner_group.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf(`%s/`, testAccConf.enterpriseSlug), + }, + }, }) }) t.Run("imports a runner group with selected orgs without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_enterprise" "enterprise" { slug = "%s" @@ -187,7 +163,7 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { visibility = "selected" selected_organization_ids = [data.github_organization.org.id] } - `, testEnterprise, testOrganization, randomID) + `, testAccConf.enterpriseSlug, testAccConf.owner, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_enterprise_actions_runner_group.test", "name"), @@ -200,27 +176,21 @@ func TestAccGithubActionsEnterpriseRunnerGroup(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_actions_runner_group.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf(`%s/`, testEnterprise), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + { + ResourceName: "github_enterprise_actions_runner_group.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf(`%s/`, testAccConf.enterpriseSlug), + }, + }, }) }) } diff --git a/github/resource_github_enterprise_actions_workflow_permissions_test.go b/github/resource_github_enterprise_actions_workflow_permissions_test.go index 252ba17d71..0bbc624306 100644 --- a/github/resource_github_enterprise_actions_workflow_permissions_test.go +++ b/github/resource_github_enterprise_actions_workflow_permissions_test.go @@ -12,39 +12,27 @@ func TestAccGithubEnterpriseActionsWorkflowPermissions(t *testing.T) { config := fmt.Sprintf(` resource "github_enterprise_actions_workflow_permissions" "test" { enterprise_slug = "%s" - + default_workflow_permissions = "read" can_approve_pull_request_reviews = false } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "default_workflow_permissions", "read"), resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "can_approve_pull_request_reviews", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -53,20 +41,20 @@ func TestAccGithubEnterpriseActionsWorkflowPermissions(t *testing.T) { "before": fmt.Sprintf(` resource "github_enterprise_actions_workflow_permissions" "test" { enterprise_slug = "%s" - + default_workflow_permissions = "read" can_approve_pull_request_reviews = false } - `, testEnterprise), + `, testAccConf.enterpriseSlug), "after": fmt.Sprintf(` resource "github_enterprise_actions_workflow_permissions" "test" { enterprise_slug = "%s" - + default_workflow_permissions = "write" can_approve_pull_request_reviews = true } - `, testEnterprise), + `, testAccConf.enterpriseSlug), } checks := map[string]resource.TestCheckFunc{ @@ -80,31 +68,19 @@ func TestAccGithubEnterpriseActionsWorkflowPermissions(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) @@ -112,44 +88,32 @@ func TestAccGithubEnterpriseActionsWorkflowPermissions(t *testing.T) { config := fmt.Sprintf(` resource "github_enterprise_actions_workflow_permissions" "test" { enterprise_slug = "%s" - + default_workflow_permissions = "read" can_approve_pull_request_reviews = false } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "default_workflow_permissions", "read"), resource.TestCheckResourceAttr("github_enterprise_actions_workflow_permissions.test", "can_approve_pull_request_reviews", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_actions_workflow_permissions.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_actions_workflow_permissions.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_enterprise_organization_test.go b/github/resource_github_enterprise_organization_test.go index f538d1b019..68497cdd13 100644 --- a/github/resource_github_enterprise_organization_test.go +++ b/github/resource_github_enterprise_organization_test.go @@ -36,7 +36,7 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName, desc) + `, testAccConf.enterpriseSlug, orgName, desc) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -67,33 +67,21 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - desc, - updatedDesc, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: strings.Replace(config, + desc, + updatedDesc, 1), + Check: checks["after"], + }, + }, }) }) @@ -118,29 +106,17 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + `, testAccConf.enterpriseSlug, orgName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -173,7 +149,7 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName, displayName, desc) + `, testAccConf.enterpriseSlug, orgName, displayName, desc) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -212,36 +188,24 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace( - strings.Replace(config, - displayName, - updatedDisplayName, 1), - desc, - updatedDesc, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: strings.Replace( + strings.Replace(config, + displayName, + updatedDisplayName, 1), + desc, + updatedDesc, 1), + Check: checks["after"], + }, + }, }) }) @@ -273,7 +237,7 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName, desc) + `, testAccConf.enterpriseSlug, orgName, desc) configWithDisplayName := fmt.Sprintf(` data "github_enterprise" "enterprise" { @@ -294,7 +258,7 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName, displayName, desc) + `, testAccConf.enterpriseSlug, orgName, displayName, desc) checks := map[string]resource.TestCheckFunc{ "create": resource.ComposeTestCheckFunc( @@ -355,50 +319,38 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configWithoutDisplayName, - Check: checks["create"], - }, - { - Config: configWithDisplayName, - Check: checks["set"], - }, - { - Config: strings.Replace(configWithDisplayName, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configWithoutDisplayName, + Check: checks["create"], + }, + { + Config: configWithDisplayName, + Check: checks["set"], + }, + { + Config: strings.Replace(configWithDisplayName, + displayName, + updatedDisplayName, 1), + Check: checks["updateDisplayName"], + }, + { + Config: strings.Replace( + strings.Replace(configWithDisplayName, displayName, updatedDisplayName, 1), - Check: checks["updateDisplayName"], - }, - { - Config: strings.Replace( - strings.Replace(configWithDisplayName, - displayName, - updatedDisplayName, 1), - desc, - updatedDesc, 1), - Check: checks["updateDesc"], - }, - { - Config: configWithoutDisplayName, - Check: checks["unset"], - }, + desc, + updatedDesc, 1), + Check: checks["updateDesc"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: configWithoutDisplayName, + Check: checks["unset"], + }, + }, }) }) @@ -423,37 +375,25 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName) + `, testAccConf.enterpriseSlug, orgName) check := resource.ComposeTestCheckFunc() - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_organization.org", - ImportState: true, - ImportStateVerify: true, - ImportStateId: fmt.Sprintf(`%s/%s`, testEnterprise, orgName), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_organization.org", + ImportState: true, + ImportStateVerify: true, + ImportStateId: fmt.Sprintf(`%s/%s`, testAccConf.enterpriseSlug, orgName), + }, + }, }) }) @@ -479,37 +419,25 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName) + `, testAccConf.enterpriseSlug, orgName) check := resource.ComposeTestCheckFunc() - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_organization.org", - ImportState: true, - ImportStateId: fmt.Sprintf(`%s/%s`, randomID, orgName), - ExpectError: regexp.MustCompile("Could not resolve to a Business with the URL slug of .*"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_organization.org", + ImportState: true, + ImportStateId: fmt.Sprintf(`%s/%s`, randomID, orgName), + ExpectError: regexp.MustCompile("Could not resolve to a Business with the URL slug of .*"), + }, + }, }) }) @@ -535,37 +463,25 @@ func TestAccGithubEnterpriseOrganization(t *testing.T) { data.github_user.current.login ] } - `, testEnterprise, orgName) + `, testAccConf.enterpriseSlug, orgName) check := resource.ComposeTestCheckFunc() - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_organization.org", - ImportState: true, - ImportStateId: fmt.Sprintf(`%s/%s`, testEnterprise, randomID), - ExpectError: regexp.MustCompile("Could not resolve to an Organization with the login of .*"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_organization.org", + ImportState: true, + ImportStateId: fmt.Sprintf(`%s/%s`, testAccConf.enterpriseSlug, randomID), + ExpectError: regexp.MustCompile("Could not resolve to an Organization with the login of .*"), + }, + }, }) }) } diff --git a/github/resource_github_enterprise_security_analysis_settings_test.go b/github/resource_github_enterprise_security_analysis_settings_test.go index eb56c63184..4c434d9618 100644 --- a/github/resource_github_enterprise_security_analysis_settings_test.go +++ b/github/resource_github_enterprise_security_analysis_settings_test.go @@ -12,43 +12,31 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { config := fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + advanced_security_enabled_for_new_repositories = true secret_scanning_enabled_for_new_repositories = true secret_scanning_push_protection_enabled_for_new_repositories = false secret_scanning_validity_checks_enabled = true } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "advanced_security_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_push_protection_enabled_for_new_repositories", "false"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_validity_checks_enabled", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -56,17 +44,17 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { config := fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + advanced_security_enabled_for_new_repositories = true secret_scanning_enabled_for_new_repositories = true secret_scanning_push_protection_enabled_for_new_repositories = true secret_scanning_push_protection_custom_link = "https://example.com/security-help" secret_scanning_validity_checks_enabled = true } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "advanced_security_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_push_protection_enabled_for_new_repositories", "true"), @@ -74,27 +62,15 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_validity_checks_enabled", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -103,25 +79,25 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { "before": fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + advanced_security_enabled_for_new_repositories = false secret_scanning_enabled_for_new_repositories = false secret_scanning_push_protection_enabled_for_new_repositories = false secret_scanning_validity_checks_enabled = false } - `, testEnterprise), + `, testAccConf.enterpriseSlug), "after": fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + advanced_security_enabled_for_new_repositories = true secret_scanning_enabled_for_new_repositories = true secret_scanning_push_protection_enabled_for_new_repositories = true secret_scanning_push_protection_custom_link = "https://updated.example.com/security" secret_scanning_validity_checks_enabled = true } - `, testEnterprise), + `, testAccConf.enterpriseSlug), } checks := map[string]resource.TestCheckFunc{ @@ -140,31 +116,19 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) @@ -173,37 +137,25 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "advanced_security_enabled_for_new_repositories", "false"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_enabled_for_new_repositories", "false"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_push_protection_enabled_for_new_repositories", "false"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_validity_checks_enabled", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + }, }) }) @@ -211,48 +163,36 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { config := fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + advanced_security_enabled_for_new_repositories = true secret_scanning_enabled_for_new_repositories = true secret_scanning_push_protection_enabled_for_new_repositories = false secret_scanning_validity_checks_enabled = true } - `, testEnterprise) + `, testAccConf.enterpriseSlug) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testEnterprise), + resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "enterprise_slug", testAccConf.enterpriseSlug), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "advanced_security_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_enabled_for_new_repositories", "true"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_push_protection_enabled_for_new_repositories", "false"), resource.TestCheckResourceAttr("github_enterprise_security_analysis_settings.test", "secret_scanning_validity_checks_enabled", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_enterprise_security_analysis_settings.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + ResourceName: "github_enterprise_security_analysis_settings.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -261,19 +201,19 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { "with_link": fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + secret_scanning_push_protection_enabled_for_new_repositories = true secret_scanning_push_protection_custom_link = "https://example.com/help" } - `, testEnterprise), + `, testAccConf.enterpriseSlug), "without_link": fmt.Sprintf(` resource "github_enterprise_security_analysis_settings" "test" { enterprise_slug = "%s" - + secret_scanning_push_protection_enabled_for_new_repositories = true } - `, testEnterprise), + `, testAccConf.enterpriseSlug), } checks := map[string]resource.TestCheckFunc{ @@ -287,31 +227,19 @@ func TestAccGithubEnterpriseSecurityAnalysisSettings(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["with_link"], - Check: checks["with_link"], - }, - { - Config: configs["without_link"], - Check: checks["without_link"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessEnterprise(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configs["with_link"], + Check: checks["with_link"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - testCase(t, enterprise) + { + Config: configs["without_link"], + Check: checks["without_link"], + }, + }, }) }) } diff --git a/github/resource_github_etag_acc_test.go b/github/resource_github_etag_acc_test.go index b4d20aee0c..ee8f634610 100644 --- a/github/resource_github_etag_acc_test.go +++ b/github/resource_github_etag_acc_test.go @@ -21,7 +21,7 @@ func TestAccGithubRepositoryEtagPresent(t *testing.T) { `, repoName) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { skipUnauthenticated(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -49,7 +49,7 @@ func TestAccGithubRepositoryEtagNoDiff(t *testing.T) { `, repoName) resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, + PreCheck: func() { skipUnauthenticated(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/resource_github_issue_label_test.go b/github/resource_github_issue_label_test.go index e8681f7798..72c50e10c9 100644 --- a/github/resource_github_issue_label_test.go +++ b/github/resource_github_issue_label_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubIssueLabel(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates labels without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) description := "label_description" updatedDescription := "updated_label_description" @@ -46,39 +45,27 @@ func TestAccGithubIssueLabel(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - description, - updatedDescription, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + description, + updatedDescription, 1), + Check: checks["after"], + }, + }, }) }) t.Run("can delete labels from archived repositories without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-archive-%s" @@ -98,50 +85,40 @@ func TestAccGithubIssueLabel(t *testing.T) { `auto_init = true archived = true`, 1) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_issue_label.test", "name", - "archived-test-label", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_issue_label.test", "name", + "archived-test-label", ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", ), - }, - // This step should succeed - the label should be removed from state - // without trying to actually delete it from the archived repo - { - Config: fmt.Sprintf(` + ), + }, + // This step should succeed - the label should be removed from state + // without trying to actually delete it from the archived repo + { + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-archive-%s" auto_init = true archived = true } `, randomID), - }, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_issue_labels_test.go b/github/resource_github_issue_labels_test.go index b45f8f2b04..6b0f6756ab 100644 --- a/github/resource_github_issue_labels_test.go +++ b/github/resource_github_issue_labels_test.go @@ -1,12 +1,10 @@ package github import ( - "context" "fmt" "strings" "testing" - "github.com/google/go-github/v67/github" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) @@ -14,107 +12,70 @@ import ( func TestAccGithubIssueLabels(t *testing.T) { t.Run("authoritatively overtakes existing labels", func(t *testing.T) { repoName := fmt.Sprintf("tf-acc-test-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) - existingLabelName := fmt.Sprintf("label-%s", acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) empty := []map[string]any{} - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - // 0. Create the repository - { - Config: testAccGithubIssueLabelsConfig(repoName, nil), - ExpectNonEmptyPlan: true, - }, - // 1. Check if some labels already exist (indicated by non-empty plan) - { - PreConfig: func() { - err := testAccGithubIssueLabelsAddLabel(repoName, existingLabelName) - if err != nil { - t.Fatalf("failed to add label: %s", existingLabelName) - } - }, - Config: testAccGithubIssueLabelsConfig(repoName, empty), - PlanOnly: true, - ExpectNonEmptyPlan: true, - }, - // 2. Check if existing labels can be adopted - { - Config: testAccGithubIssueLabelsConfig(repoName, append(empty, map[string]any{ - "name": existingLabelName, - "color": "000000", - "description": "Test label", - })), - Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "1"), - }, - // 3. Check if all the labels are destroyed when the resource has no labels - { - Config: testAccGithubIssueLabelsConfig(repoName, empty), - Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "0"), - }, - // 4. Check if a new label can be created - { - Config: testAccGithubIssueLabelsConfig(repoName, append(empty, map[string]any{ - "name": "foo", - "color": "000000", - "description": "foo", - })), - Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "1"), - }, - // 5. Check if a label can be recreated - { - Config: testAccGithubIssueLabelsConfig(repoName, append(empty, map[string]any{ + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + // 0. Check if some labels already exist (indicated by non-empty plan) + { + Config: testAccGithubIssueLabelsConfig(repoName, empty), + PlanOnly: true, + ExpectNonEmptyPlan: true, + }, + // 1. Check if all the labels are destroyed when the resource is added + { + Config: testAccGithubIssueLabelsConfig(repoName, empty), + Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "0"), + }, + // 2. Check if a label can be created + { + Config: testAccGithubIssueLabelsConfig(repoName, append(empty, map[string]any{ + "name": "foo", + "color": "000000", + "description": "foo", + })), + Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "1"), + }, + // 3. Check if a label can be recreated + { + Config: testAccGithubIssueLabelsConfig(repoName, append(empty, map[string]any{ + "name": "Foo", + "color": "000000", + "description": "foo", + })), + Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "1"), + }, + // 4. Check if multiple labels can be created + { + Config: testAccGithubIssueLabelsConfig(repoName, append(empty, + map[string]any{ "name": "Foo", "color": "000000", "description": "foo", + }, + map[string]any{ + "name": "bar", + "color": "000000", + "description": "bar", + }, map[string]any{ + "name": "baz", + "color": "000000", + "description": "baz", })), - Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "1"), - }, - // 6. Check if multiple labels can be created - { - Config: testAccGithubIssueLabelsConfig(repoName, append(empty, - map[string]any{ - "name": "Foo", - "color": "000000", - "description": "foo", - }, - map[string]any{ - "name": "bar", - "color": "000000", - "description": "bar", - }, map[string]any{ - "name": "baz", - "color": "000000", - "description": "baz", - })), - Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "3"), - }, - // 7. Check if labels can be destroyed - { - Config: testAccGithubIssueLabelsConfig(repoName, nil), - ExpectNonEmptyPlan: true, - }, - // 8. Check if labels were actually destroyed - { - Config: testAccGithubIssueLabelsConfig(repoName, empty), - PlanOnly: true, - ExpectNonEmptyPlan: true, - }, + Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "3"), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + // 5. Check if labels can be destroyed + { + Config: testAccGithubIssueLabelsConfig(repoName, nil), + }, + // 6. Check if labels were actually destroyed + { + Config: testAccGithubIssueLabelsConfig(repoName, empty), + Check: resource.TestCheckResourceAttr("github_issue_labels.test", "label.#", "0"), + }, + }, }) }) } @@ -152,15 +113,6 @@ func testAccGithubIssueLabelsConfig(repoName string, labels []map[string]any) st `, repoName, resource) } -func testAccGithubIssueLabelsAddLabel(repository, label string) error { - client := testAccProvider.Meta().(*Owner).v3client - orgName := testAccProvider.Meta().(*Owner).name - ctx := context.TODO() - - _, _, err := client.Issues.CreateLabel(ctx, orgName, repository, &github.Label{Name: github.String(label)}) - return err -} - func TestAccGithubIssueLabelsArchived(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) @@ -181,7 +133,7 @@ func TestAccGithubIssueLabelsArchived(t *testing.T) { description = "First test label" } label { - name = "archived-label-2" + name = "archived-label-2" color = "00ff00" description = "Second test label" } @@ -193,50 +145,40 @@ func TestAccGithubIssueLabelsArchived(t *testing.T) { `auto_init = true archived = true`, 1) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_issue_labels.test", "label.#", - "2", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_issue_labels.test", "label.#", + "2", ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", ), - }, - // This step should succeed - the labels should be removed from state - // without trying to actually delete them from the archived repo - { - Config: fmt.Sprintf(` + ), + }, + // This step should succeed - the labels should be removed from state + // without trying to actually delete them from the archived repo + { + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true archived = true } `, repoName), - }, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_issue_test.go b/github/resource_github_issue_test.go index d64338a5b8..db084a21de 100644 --- a/github/resource_github_issue_test.go +++ b/github/resource_github_issue_test.go @@ -11,9 +11,8 @@ import ( ) func TestAccGithubIssue(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates an issue without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) title := "issue_title" body := "issue_body" labels := "\"bug\", \"enhancement\"" @@ -46,7 +45,7 @@ func TestAccGithubIssue(t *testing.T) { milestone_number = github_repository_milestone.test.number } ` - config := fmt.Sprintf(issueHCL, randomID, title, body, labels, testOwnerFunc()) + config := fmt.Sprintf(issueHCL, randomID, title, body, labels, testAccConf.username) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -93,37 +92,24 @@ func TestAccGithubIssue(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: fmt.Sprintf(issueHCL, randomID, updatedTitle, updatedBody, updatedLabels, testOwnerFunc()), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: fmt.Sprintf(issueHCL, randomID, updatedTitle, updatedBody, updatedLabels, testAccConf.owner), + Check: checks["after"], + }, + }, }) }) t.Run("imports a issue without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -141,34 +127,20 @@ func TestAccGithubIssue(t *testing.T) { resource.TestCheckResourceAttr("github_issue.test", "title", fmt.Sprintf(`tf-acc-test-%s`, randomID)), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_issue.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_issue.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_membership_test.go b/github/resource_github_membership_test.go index e107363cb3..004a26b609 100644 --- a/github/resource_github_membership_test.go +++ b/github/resource_github_membership_test.go @@ -11,116 +11,108 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccGithubMembership_basic(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") - } - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) +func TestAccGithubMembership(t *testing.T) { + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") } - var membership github.Membership - rn := "github_membership.test_org_membership" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubMembershipDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubMembershipConfig(testCollaborator), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubMembershipExists(rn, &membership), - testAccCheckGithubMembershipRoleState(rn, &membership), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + t.Run("creates organization membership", func(t *testing.T) { + ctx := t.Context() + + var membership github.Membership + rn := "github_membership.test_org_membership" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubMembershipDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubMembershipConfig(testAccConf.testExternalUser), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubMembershipExists(ctx, rn, &membership), + testAccCheckGithubMembershipRoleState(ctx, rn, &membership), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, }, - }, + }) }) -} -func TestAccGithubMembership_downgrade(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") - } - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - var membership github.Membership - rn := "github_membership.test_org_membership" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubMembershipDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubMembershipConfigDowngradable(testCollaborator), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubMembershipExists(rn, &membership), - testAccCheckGithubMembershipRoleState(rn, &membership), - ), - }, - { - ResourceName: rn, - ImportState: true, + t.Run("creates organization membership with downgrade", func(t *testing.T) { + ctx := t.Context() + + var membership github.Membership + rn := "github_membership.test_org_membership" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubMembershipDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubMembershipConfigDowngradable(testAccConf.testExternalUser), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubMembershipExists(ctx, rn, &membership), + testAccCheckGithubMembershipRoleState(ctx, rn, &membership), + ), + }, + { + ResourceName: rn, + ImportState: true, + }, }, - }, + }) }) -} - -func TestAccGithubMembership_caseInsensitive(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") - } - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - var membership github.Membership - var otherMembership github.Membership - - rn := "github_membership.test_org_membership" - otherCase := flipUsernameCase(testCollaborator) - if testCollaborator == otherCase { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` has no letters to flip case") - } - - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubMembershipDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubMembershipConfig(testCollaborator), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubMembershipExists(rn, &membership), - ), - }, - { - Config: testAccGithubMembershipConfig(otherCase), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubMembershipExists(rn, &otherMembership), - testAccGithubMembershipTheSame(&membership, &otherMembership), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + t.Run("creates organization membership with case insensitivity", func(t *testing.T) { + ctx := t.Context() + + var membership github.Membership + var otherMembership github.Membership + + rn := "github_membership.test_org_membership" + otherCase := flipUsernameCase(testAccConf.testExternalUser) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubMembershipDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubMembershipConfig(testAccConf.testExternalUser), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubMembershipExists(ctx, rn, &membership), + ), + }, + { + Config: testAccGithubMembershipConfig(otherCase), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubMembershipExists(ctx, rn, &otherMembership), + testAccGithubMembershipTheSame(&membership, &otherMembership), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, }, - }, + }) }) } func testAccCheckGithubMembershipDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client + ctx := context.Background() + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client for _, rs := range s.RootModule().Resources { if rs.Type != "github_membership" { @@ -133,7 +125,7 @@ func testAccCheckGithubMembershipDestroy(s *terraform.State) error { } downgradedOnDestroy := rs.Primary.Attributes["downgrade_on_destroy"] == "true" - membership, resp, err := conn.Organizations.GetOrgMembership(context.TODO(), username, orgName) + membership, resp, err := conn.Organizations.GetOrgMembership(ctx, username, orgName) responseIsSuccessful := err == nil && membership != nil && buildTwoPartID(orgName, username) == rs.Primary.ID if downgradedOnDestroy { @@ -146,7 +138,7 @@ func testAccCheckGithubMembershipDestroy(s *terraform.State) error { } // Now actually remove them from the org to clean up - _, removeErr := conn.Organizations.RemoveOrgMembership(context.TODO(), username, orgName) + _, removeErr := conn.Organizations.RemoveOrgMembership(ctx, username, orgName) if removeErr != nil { return fmt.Errorf("organization membership %q could not be removed during membership downgrade test case cleanup: %w", rs.Primary.ID, removeErr) } @@ -161,7 +153,7 @@ func testAccCheckGithubMembershipDestroy(s *terraform.State) error { return nil } -func testAccCheckGithubMembershipExists(n string, membership *github.Membership) resource.TestCheckFunc { +func testAccCheckGithubMembershipExists(ctx context.Context, n string, membership *github.Membership) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -172,13 +164,18 @@ func testAccCheckGithubMembershipExists(n string, membership *github.Membership) return fmt.Errorf("no membership ID is set") } - conn := testAccProvider.Meta().(*Owner).v3client + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName, username, err := parseTwoPartID(rs.Primary.ID, "organization", "username") if err != nil { return err } - githubMembership, _, err := conn.Organizations.GetOrgMembership(context.TODO(), username, orgName) + githubMembership, _, err := conn.Organizations.GetOrgMembership(ctx, username, orgName) if err != nil { return err } @@ -187,7 +184,7 @@ func testAccCheckGithubMembershipExists(n string, membership *github.Membership) } } -func testAccCheckGithubMembershipRoleState(n string, membership *github.Membership) resource.TestCheckFunc { +func testAccCheckGithubMembershipRoleState(ctx context.Context, n string, membership *github.Membership) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -198,13 +195,18 @@ func testAccCheckGithubMembershipRoleState(n string, membership *github.Membersh return fmt.Errorf("no membership ID is set") } - conn := testAccProvider.Meta().(*Owner).v3client + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName, username, err := parseTwoPartID(rs.Primary.ID, "organization", "username") if err != nil { return err } - githubMembership, _, err := conn.Organizations.GetOrgMembership(context.TODO(), username, orgName) + githubMembership, _, err := conn.Organizations.GetOrgMembership(ctx, username, orgName) if err != nil { return err } diff --git a/github/resource_github_organization_custom_properties.go b/github/resource_github_organization_custom_properties.go index da400db9dd..59b035f6b3 100644 --- a/github/resource_github_organization_custom_properties.go +++ b/github/resource_github_organization_custom_properties.go @@ -85,16 +85,19 @@ func resourceGithubCustomPropertiesCreate(d *schema.ResourceData, meta any) erro for _, v := range allowedValues { allowedValuesString = append(allowedValuesString, v.(string)) } - valuesEditableBy := d.Get("values_editable_by").(string) customProperty := &github.CustomProperty{ - PropertyName: &propertyName, - ValueType: valueType, - Required: &required, - DefaultValue: &defaultValue, - Description: &description, - AllowedValues: allowedValuesString, - ValuesEditableBy: &valuesEditableBy, + PropertyName: &propertyName, + ValueType: valueType, + Required: &required, + DefaultValue: &defaultValue, + Description: &description, + AllowedValues: allowedValuesString, + } + + if val, ok := d.GetOk("values_editable_by"); ok { + str := val.(string) + customProperty.ValuesEditableBy = &str } customProperty, _, err := client.Organizations.CreateOrUpdateCustomProperty(ctx, ownerName, d.Get("property_name").(string), customProperty) diff --git a/github/resource_github_organization_custom_properties_test.go b/github/resource_github_organization_custom_properties_test.go index 4d5598d62d..ae7a1aaf9a 100644 --- a/github/resource_github_organization_custom_properties_test.go +++ b/github/resource_github_organization_custom_properties_test.go @@ -19,29 +19,15 @@ func TestAccGithubOrganizationCustomPropertiesValidation(t *testing.T) { values_editable_by = "invalid_value" }` - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile("invalid_value is an invalid value"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("invalid_value is an invalid value"), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } @@ -64,28 +50,19 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { "property_name", "Test", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) + t.Run("create custom property and update them", func(t *testing.T) { configBefore := ` resource "github_organization_custom_properties" "test" { @@ -112,33 +89,19 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "allowed_values.#", "2"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configBefore, - Check: checkBefore, - }, - { - Config: configAfter, - Check: checkAfter, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configBefore, + Check: checkBefore, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configAfter, + Check: checkAfter, + }, + }, }) }) @@ -161,33 +124,20 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_organization_custom_properties.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_organization_custom_properties.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -212,29 +162,15 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -259,29 +195,15 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -313,33 +235,19 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configBefore, - Check: checkBefore, - }, - { - Config: configAfter, - Check: checkAfter, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configBefore, + Check: checkBefore, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configAfter, + Check: checkAfter, + }, + }, }) }) @@ -369,49 +277,35 @@ func TestAccGithubOrganizationCustomProperties(t *testing.T) { const resourceName = "github_organization_custom_properties.test" - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - // First, create a property with values_editable_by set - Config: configWithField, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), - ), - }, - { - // Simulate the scenario: config doesn't have values_editable_by - // (as it would have been before Terraform support was added) - // Terraform should read the existing value from the API - Config: configWithoutField, - Check: resource.ComposeTestCheckFunc( - // Terraform should still see the value from the API - resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), - ), - }, - { - // Now add it back to the config - should be no changes needed - Config: configWithField, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + // First, create a property with values_editable_by set + Config: configWithField, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + // Simulate the scenario: config doesn't have values_editable_by + // (as it would have been before Terraform support was added) + // Terraform should read the existing value from the API + Config: configWithoutField, + Check: resource.ComposeTestCheckFunc( + // Terraform should still see the value from the API + resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), + ), + }, + { + // Now add it back to the config - should be no changes needed + Config: configWithField, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(resourceName, "values_editable_by", "org_and_repo_actors"), + ), + }, + }, }) }) } diff --git a/github/resource_github_organization_custom_role_test.go b/github/resource_github_organization_custom_role_test.go index d2bfe88e16..25af7af271 100644 --- a/github/resource_github_organization_custom_role_test.go +++ b/github/resource_github_organization_custom_role_test.go @@ -9,167 +9,96 @@ import ( ) func TestAccGithubOrganizationCustomRole(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates custom repo role without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_organization_custom_role" "test" { - name = "tf-acc-test-%s" - description = "Test role description" - base_role = "read" - permissions = [ - "reopen_issue", - "reopen_pull_request", - ] - } + resource "github_organization_custom_role" "test" { + name = "tf-acc-test-%s" + description = "Test role description" + base_role = "read" + permissions = [ + "reopen_issue", + "reopen_pull_request", + ] + } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_organization_custom_role.test", "name", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "name", - fmt.Sprintf(`tf-acc-test-%s`, randomID), - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "description", - "Test role description", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "base_role", - "read", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "permissions.#", - "2", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_organization_custom_role.test", "name"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "description", "Test role description"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "base_role", "read"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "2"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) // More tests can go here following the same format... t.Run("updates custom repo role without error", func(t *testing.T) { - configs := map[string]string{ - "before": fmt.Sprintf(` - resource "github_organization_custom_role" "test" { - name = "tf-acc-test-%s" - description = "Updated test role description before" - base_role = "read" - permissions = [ - "reopen_issue", - "reopen_pull_request", - ] - } - `, randomID), - "after": fmt.Sprintf(` - resource "github_organization_custom_role" "test" { - name = "tf-acc-test-rename-%s" - description = "Updated test role description after" - base_role = "write" - permissions = [ - "reopen_issue", - "read_code_scanning", - "reopen_pull_request", - ] - } - `, randomID), + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_organization_custom_role" "test" { + name = "tf-acc-test-%s" + description = "Updated test role description before" + base_role = "read" + permissions = [ + "reopen_issue", + "reopen_pull_request", + ] } + `, randomID) - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_organization_custom_role.test", "name", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "name", - fmt.Sprintf(`tf-acc-test-%s`, randomID), - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "description", - "Updated test role description before", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "base_role", - "read", - ), - resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "2"), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_organization_custom_role.test", "name", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "name", - fmt.Sprintf(`tf-acc-test-rename-%s`, randomID), - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "description", - "Updated test role description after", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "base_role", - "write", - ), - resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "3"), - ), + configUpdated := fmt.Sprintf(` + resource "github_organization_custom_role" "test" { + name = "tf-acc-test-rename-%s" + description = "Updated test role description after" + base_role = "write" + permissions = [ + "reopen_issue", + "read_code_scanning", + "reopen_pull_request", + ] } + `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_organization_custom_role.test", "name"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "description", "Updated test role description before"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "base_role", "read"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "2"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_organization_custom_role.test", "name"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "name", fmt.Sprintf(`tf-acc-test-rename-%s`, randomID)), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "description", "Updated test role description after"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "base_role", "write"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "3"), + ), + }, + }, }) }) t.Run("imports custom repo role without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_organization_custom_role" "test" { name = "tf-acc-test-%s" @@ -183,56 +112,21 @@ func TestAccGithubOrganizationCustomRole(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet( - "github_organization_custom_role.test", "name", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "name", - fmt.Sprintf(`tf-acc-test-%s`, randomID), - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "description", - "Test role description", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "base_role", - "read", - ), - resource.TestCheckResourceAttr( - "github_organization_custom_role.test", "permissions.#", - "3", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_organization_custom_role.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_organization_custom_role.test", "name"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "description", "Test role description"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "base_role", "read"), + resource.TestCheckResourceAttr("github_organization_custom_role.test", "permissions.#", "3"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_organization_project_test.go b/github/resource_github_organization_project_test.go index e8a4170a62..d2dff7549c 100644 --- a/github/resource_github_organization_project_test.go +++ b/github/resource_github_organization_project_test.go @@ -13,42 +13,50 @@ import ( ) func TestAccGithubOrganizationProject_basic(t *testing.T) { - t.Skip("Skipping test as the GitHub REST API no longer supports classic projects") + t.Skip("Skipping test as the GitHub API no longer supports classic projects") - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } + t.Run("creates organization project", func(t *testing.T) { + var project github.Project + config := ` +resource "github_organization_project" "test" { + name = "test-project" + body = "this is a test project" +} +` - var project github.Project - - rn := "github_organization_project.test" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccGithubOrganizationProjectDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubOrganizationProjectConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubOrganizationProjectExists(rn, &project), - testAccCheckGithubOrganizationProjectAttributes(&project, &testAccGithubOrganizationProjectExpectedAttributes{ - Name: "test-project", - Body: "this is a test project", - }), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + rn := "github_organization_project.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccGithubOrganizationProjectDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubOrganizationProjectExists(rn, &project), + testAccCheckGithubOrganizationProjectAttributes(&project, &testAccGithubOrganizationProjectExpectedAttributes{ + Name: "test-project", + Body: "this is a test project", + }), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, }, - }, + }) }) } func testAccGithubOrganizationProjectDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client for _, rs := range s.RootModule().Resources { if rs.Type != "github_organization_project" { @@ -60,7 +68,7 @@ func testAccGithubOrganizationProjectDestroy(s *terraform.State) error { return err } - project, res, err := conn.Projects.GetProject(context.TODO(), projectID) + project, res, err := conn.Projects.GetProject(context.Background(), projectID) if err == nil { if project != nil && project.GetID() == projectID { @@ -87,8 +95,13 @@ func testAccCheckGithubOrganizationProjectExists(n string, project *github.Proje return err } - conn := testAccProvider.Meta().(*Owner).v3client - gotProject, _, err := conn.Projects.GetProject(context.TODO(), projectID) + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + + gotProject, _, err := conn.Projects.GetProject(context.Background(), projectID) if err != nil { return err } @@ -117,10 +130,3 @@ func testAccCheckGithubOrganizationProjectAttributes(project *github.Project, wa return nil } } - -const testAccGithubOrganizationProjectConfig = ` -resource "github_organization_project" "test" { - name = "test-project" - body = "this is a test project" -} -` diff --git a/github/resource_github_organization_role_team_assignment_test.go b/github/resource_github_organization_role_team_assignment_test.go index c7ce92a9bb..e56f270344 100644 --- a/github/resource_github_organization_role_team_assignment_test.go +++ b/github/resource_github_organization_role_team_assignment_test.go @@ -9,8 +9,6 @@ import ( ) func TestAccGithubOrganizationRoleTeamAssignment(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - // Using the predefined roles since custom roles are a strictly Enterprise feature ((https://github.blog/changelog/2024-07-10-pre-defined-organization-roles-that-grant-access-to-all-repositories/)) githubPredefinedRoleMapping := make(map[string]string) githubPredefinedRoleMapping["all_repo_read"] = "8132" @@ -20,7 +18,9 @@ func TestAccGithubOrganizationRoleTeamAssignment(t *testing.T) { githubPredefinedRoleMapping["all_repo_admin"] = "8136" t.Run("creates repo assignment without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) teamSlug := fmt.Sprintf("tf-acc-test-team-repo-%s", randomID) + config := fmt.Sprintf(` resource "github_team" "test" { name = "%s" @@ -44,35 +44,23 @@ func TestAccGithubOrganizationRoleTeamAssignment(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) // More tests can go here following the same format... t.Run("create and re-creates role assignment without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) teamSlug := fmt.Sprintf("tf-acc-test-team-repo-%s", randomID) + configs := map[string]string{ "before": fmt.Sprintf(` resource "github_team" "test" { @@ -109,33 +97,19 @@ func TestAccGithubOrganizationRoleTeamAssignment(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) } diff --git a/github/resource_github_organization_role_team_test.go b/github/resource_github_organization_role_team_test.go index 266871b4c0..3df806863e 100644 --- a/github/resource_github_organization_role_team_test.go +++ b/github/resource_github_organization_role_team_test.go @@ -26,7 +26,7 @@ func TestAccGithubOrganizationRoleTeam(t *testing.T) { `, teamName, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/resource_github_organization_role_user_test.go b/github/resource_github_organization_role_user_test.go index 072c470d62..78bde9e5be 100644 --- a/github/resource_github_organization_role_user_test.go +++ b/github/resource_github_organization_role_user_test.go @@ -25,7 +25,7 @@ func TestAccGithubOrganizationRoleUser(t *testing.T) { `, roleId, login) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { diff --git a/github/resource_github_organization_ruleset_test.go b/github/resource_github_organization_ruleset_test.go index dcb999b514..f841305140 100644 --- a/github/resource_github_organization_ruleset_test.go +++ b/github/resource_github_organization_ruleset_test.go @@ -11,17 +11,9 @@ import ( ) func TestGithubOrganizationRulesets(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("Creates and updates organization rulesets without errors", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_organization_ruleset" "test" { name = "test-%s" @@ -29,6 +21,11 @@ func TestGithubOrganizationRulesets(t *testing.T) { enforcement = "active" conditions { + repository_name { + include = ["~ALL"] + exclude = [] + } + ref_name { include = ["~ALL"] exclude = [] @@ -91,125 +88,103 @@ func TestGithubOrganizationRulesets(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", - "name", - "test", - ), - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", - "enforcement", - "active", - ), - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", - "rules.0.required_workflows.0.do_not_enforce_on_create", - "true", - ), - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", - "rules.0.required_workflows.0.required_workflow.0.path", - "path/to/workflow.yaml", - ), - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", - "rules.0.required_workflows.0.required_workflow.0.repository_id", - "1234", - ), - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", - "rules.0.required_code_scanning.0.required_code_scanning_tool.0.alerts_threshold", - "errors", - ), - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", - "rules.0.required_code_scanning.0.required_code_scanning_tool.0.security_alerts_threshold", - "high_or_higher", - ), - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", - "rules.0.required_code_scanning.0.required_code_scanning_tool.0.tool", - "CodeQL", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_organization_ruleset.test", "name", "test"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "enforcement", "active"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_workflows.0.do_not_enforce_on_create", "true"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_workflows.0.required_workflow.0.path", "path/to/workflow.yaml"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_workflows.0.required_workflow.0.repository_id", "1234"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_code_scanning.0.required_code_scanning_tool.0.alerts_threshold", "errors"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_code_scanning.0.required_code_scanning_tool.0.security_alerts_threshold", "high_or_higher"), + resource.TestCheckResourceAttr("github_organization_ruleset.test", "rules.0.required_code_scanning.0.required_code_scanning_tool.0.tool", "CodeQL"), + ), }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) t.Run("Updates a ruleset name without error", func(t *testing.T) { - oldRSName := fmt.Sprintf(`ruleset-%[1]s`, randomID) - newRSName := fmt.Sprintf(`%[1]s-renamed`, randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + name := fmt.Sprintf("test-acc-ruleset-%s", randomID) + nameUpdated := fmt.Sprintf("test-acc-ruleset-updated-%s", randomID) config := fmt.Sprintf(` - resource "github_organization_ruleset" "test" { - name = "%s" - target = "branch" - enforcement = "active" + resource "github_organization_ruleset" "test" { + name = "%s" + target = "branch" + enforcement = "active" + + conditions { + repository_name { + include = ["~ALL"] + exclude = [] + } - rules { - creation = true + ref_name { + include = ["~ALL"] + exclude = [] } } - `, oldRSName) - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", "name", - oldRSName, - ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_organization_ruleset.test", "name", - newRSName, - ), - ), + rules { + creation = true + } } + `, name) + + configUpdated := fmt.Sprintf(` + resource "github_organization_ruleset" "test" { + name = "%s" + target = "branch" + enforcement = "active" + + conditions { + repository_name { + include = ["~ALL"] + exclude = [] + } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - // Rename the ruleset to something else - Config: strings.Replace( - config, - oldRSName, - newRSName, 1), - Check: checks["after"], - }, - }, - }) - } + ref_name { + include = ["~ALL"] + exclude = [] + } + } - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + rules { + creation = true + } + } + `, nameUpdated) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_organization_ruleset.test", "name", name), + ), + }, + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_organization_ruleset.test", "name", nameUpdated), + ), + }, + }, }) }) - t.Run("Imports rulesets without error", func(t *testing.T) { + t.Run("imports rulesets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_organization_ruleset" "test" { name = "test-%s" @@ -217,6 +192,11 @@ func TestGithubOrganizationRulesets(t *testing.T) { enforcement = "active" conditions { + repository_name { + include = ["~ALL"] + exclude = [] + } + ref_name { include = ["~ALL"] exclude = [] @@ -248,7 +228,6 @@ func TestGithubOrganizationRulesets(t *testing.T) { } strict_required_status_checks_policy = true - do_not_enforce_on_create = true } branch_name_pattern { @@ -261,36 +240,32 @@ func TestGithubOrganizationRulesets(t *testing.T) { non_fast_forward = true } } - `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_organization_ruleset.test", "name"), - ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_organization_ruleset.test", - ImportState: true, - ImportStateVerify: true, - }, - }, - }) - } + `, randomID) - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + ResourceName: "github_organization_ruleset.test", + ImportState: true, + ImportStateVerify: true, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_organization_ruleset.test", "name"), + ), + }, + }, }) }) t.Run("Creates and updates organization using bypasses", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_organization_ruleset" "test" { name = "test-%s" @@ -377,25 +352,21 @@ func TestGithubOrganizationRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) t.Run("Creates organization ruleset with all bypass_modes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_organization_ruleset" "test" { name = "test-bypass-modes-%s" @@ -476,25 +447,21 @@ func TestGithubOrganizationRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) t.Run("Updates organization ruleset bypass_mode without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_organization_ruleset" "test" { name = "test-bypass-update-%s" @@ -542,25 +509,19 @@ func TestGithubOrganizationRulesets(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: configUpdated, - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + { + Config: configUpdated, + Check: checks["after"], + }, + }, }) }) } diff --git a/github/resource_github_organization_security_manager_test.go b/github/resource_github_organization_security_manager_test.go index 5fec6a7486..4f3dc94907 100644 --- a/github/resource_github_organization_security_manager_test.go +++ b/github/resource_github_organization_security_manager_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubOrganizationSecurityManager(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("adds team as security manager", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -22,37 +21,24 @@ func TestAccGithubOrganizationSecurityManager(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), - resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), - resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), + resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), + resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("handles team name changes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -73,45 +59,32 @@ func TestAccGithubOrganizationSecurityManager(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), - resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), - resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), - ), - }, - { - Config: configUpdated, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), - resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), - resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-updated-%s", randomID)), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), + resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), + resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), + resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), + resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-updated-%s", randomID)), + ), + }, + }, }) }) t.Run("handles team name changes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -132,41 +105,27 @@ func TestAccGithubOrganizationSecurityManager(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), - resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), - resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), - ), - }, - { - Config: configUpdated, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), - resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), - resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-updated-%s", randomID)), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), + resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), + resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-%s", randomID)), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrPair("github_team.test", "ID", "github_organization_security_manager.test", "ID"), + resource.TestCheckResourceAttrPair("github_team.test", "slug", "github_organization_security_manager.test", "team_slug"), + resource.TestCheckResourceAttr("github_organization_security_manager.test", "team_slug", fmt.Sprintf("tf-acc-updated-%s", randomID)), + ), + }, + }, }) }) } diff --git a/github/resource_github_organization_settings_test.go b/github/resource_github_organization_settings_test.go index 6be37c6e54..2f32c9a060 100644 --- a/github/resource_github_organization_settings_test.go +++ b/github/resource_github_organization_settings_test.go @@ -8,6 +8,8 @@ import ( ) func TestAccGithubOrganizationSettings(t *testing.T) { + t.Skip("TODO: Make this test cleanup correctly") + t.Run("creates organization settings without error", func(t *testing.T) { config := ` resource "github_organization_settings" "test" { @@ -45,28 +47,19 @@ func TestAccGithubOrganizationSettings(t *testing.T) { "billing_email", "test@example.com", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) + t.Run("updates organization settings without error", func(t *testing.T) { billingEmail := "test1@example.com" company := "Test Company" @@ -100,33 +93,19 @@ func TestAccGithubOrganizationSettings(t *testing.T) { "billing_email", updatedBillingEmail, ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) @@ -149,33 +128,20 @@ func TestAccGithubOrganizationSettings(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_organization_settings.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_organization_settings.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -241,26 +207,16 @@ func TestAccGithubOrganizationSettings(t *testing.T) { "secret_scanning_push_protection_enabled_for_new_repositories", "false", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -326,26 +282,16 @@ func TestAccGithubOrganizationSettings(t *testing.T) { "secret_scanning_push_protection_enabled_for_new_repositories", "true", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -361,26 +307,16 @@ func TestAccGithubOrganizationSettings(t *testing.T) { "billing_email", "test@example.com", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -409,8 +345,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "blog", "https://test.com/blog"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -418,16 +354,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -453,8 +379,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "secret_scanning_push_protection_enabled_for_new_repositories", "true"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -462,16 +388,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -495,8 +411,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "members_can_create_private_pages", "true"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -504,16 +420,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -533,8 +439,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "has_repository_projects", "true"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -542,16 +448,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -567,8 +463,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "default_repository_permission", "write"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -576,16 +472,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -600,20 +486,20 @@ func TestAccGithubOrganizationSettings(t *testing.T) { name = "Test Organization" description = "Test organization description" blog = "https://test.com/blog" - + advanced_security_enabled_for_new_repositories = true dependabot_alerts_enabled_for_new_repositories = true dependabot_security_updates_enabled_for_new_repositories = true dependency_graph_enabled_for_new_repositories = true secret_scanning_enabled_for_new_repositories = true secret_scanning_push_protection_enabled_for_new_repositories = true - + members_can_create_private_repositories = true members_can_create_internal_repositories = true members_can_create_pages = true members_can_create_public_pages = true members_can_create_private_pages = true - + web_commit_signoff_required = true default_repository_permission = "write" }` @@ -642,8 +528,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "default_repository_permission", "write"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -651,16 +537,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -698,8 +574,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "web_commit_signoff_required", "false"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -707,16 +583,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) @@ -732,8 +598,8 @@ func TestAccGithubOrganizationSettings(t *testing.T) { resource.TestCheckResourceAttr("github_organization_settings.test", "default_repository_permission", "admin"), ) - testCase := resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -741,16 +607,6 @@ func TestAccGithubOrganizationSettings(t *testing.T) { Check: check, }, }, - } - - t.Run("run with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("run with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("run with an organization account", func(t *testing.T) { - resource.Test(t, testCase) }) }) }) diff --git a/github/resource_github_organization_webhook_test.go b/github/resource_github_organization_webhook_test.go index ca2d6c090c..7cf063bb33 100644 --- a/github/resource_github_organization_webhook_test.go +++ b/github/resource_github_organization_webhook_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubOrganizationWebhook(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -47,39 +46,26 @@ func TestAccGithubOrganizationWebhook(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - "https://google.de/webhook", - "https://google.de/updated", 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + "https://google.de/webhook", + "https://google.de/updated", 1), + Check: checks["after"], + }, + }, }) }) t.Run("imports webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -106,34 +92,20 @@ func TestAccGithubOrganizationWebhook(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_organization_webhook.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_organization_webhook.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_project_card_test.go b/github/resource_github_project_card_test.go index facbd1a703..699def81c7 100644 --- a/github/resource_github_project_card_test.go +++ b/github/resource_github_project_card_test.go @@ -11,11 +11,10 @@ import ( ) func TestAccGithubProjectCard(t *testing.T) { - t.Skip("Skipping test as the GitHub REST API no longer supports classic projects") - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + t.Skip("Skipping test as the GitHub API no longer supports classic projects") t.Run("creates a project card using a note", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_organization_project" "project" { @@ -41,33 +40,20 @@ func TestAccGithubProjectCard(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates a project card using an issue", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -97,6 +83,7 @@ func TestAccGithubProjectCard(t *testing.T) { column_id = github_project_column.test.column_id content_id = github_issue.test.issue_id content_type = "Issue" + content_type = "Issue" } `, randomID) @@ -116,29 +103,15 @@ func TestAccGithubProjectCard(t *testing.T) { }, ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_project_column_test.go b/github/resource_github_project_column_test.go index 0b3f86bcb7..1dd253f97f 100644 --- a/github/resource_github_project_column_test.go +++ b/github/resource_github_project_column_test.go @@ -12,50 +12,52 @@ import ( ) func TestAccGithubProjectColumn_basic(t *testing.T) { - t.Skip("Skipping test as the GitHub REST API no longer supports classic projects") - - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - var column github.ProjectColumn - - rn := "github_project_column.column" - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccGithubProjectColumnDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubProjectColumnConfig("new column name"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubProjectColumnExists(rn, &column), - testAccCheckGithubProjectColumnAttributes(&column, &testAccGithubProjectColumnExpectedAttributes{ - Name: "new column name", - }), - ), - }, - { - Config: testAccGithubProjectColumnConfig("updated column name"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubProjectColumnExists(rn, &column), - testAccCheckGithubProjectColumnAttributes(&column, &testAccGithubProjectColumnExpectedAttributes{ - Name: "updated column name", - }), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + t.Skip("Skipping test as the GitHub API no longer supports classic projects") + + t.Run("creates and updates a project column", func(t *testing.T) { + var column github.ProjectColumn + + rn := "github_project_column.column" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccGithubProjectColumnDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubProjectColumnConfig("new column name"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubProjectColumnExists(rn, &column), + testAccCheckGithubProjectColumnAttributes(&column, &testAccGithubProjectColumnExpectedAttributes{ + Name: "new column name", + }), + ), + }, + { + Config: testAccGithubProjectColumnConfig("updated column name"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubProjectColumnExists(rn, &column), + testAccCheckGithubProjectColumnAttributes(&column, &testAccGithubProjectColumnExpectedAttributes{ + Name: "updated column name", + }), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, }, - }, + }) }) } func testAccGithubProjectColumnDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client for _, rs := range s.RootModule().Resources { if rs.Type != "github_project_column" { @@ -67,7 +69,7 @@ func testAccGithubProjectColumnDestroy(s *terraform.State) error { return err } - column, res, err := conn.Projects.GetProjectColumn(context.TODO(), columnID) + column, res, err := conn.Projects.GetProjectColumn(context.Background(), columnID) if err == nil { if column != nil && column.GetID() == columnID { @@ -93,8 +95,13 @@ func testAccCheckGithubProjectColumnExists(n string, project *github.ProjectColu return err } - conn := testAccProvider.Meta().(*Owner).v3client - gotColumn, _, err := conn.Projects.GetProjectColumn(context.TODO(), columnID) + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + + gotColumn, _, err := conn.Projects.GetProjectColumn(context.Background(), columnID) if err != nil { return err } diff --git a/github/resource_github_release_test.go b/github/resource_github_release_test.go index eddedfba4c..b9f28a8195 100644 --- a/github/resource_github_release_test.go +++ b/github/resource_github_release_test.go @@ -55,36 +55,22 @@ func TestAccGithubReleaseResource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_release.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importReleaseByResourcePaths( - "github_repository.test", "github_release.test"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_release.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importReleaseByResourcePaths( + "github_repository.test", "github_release.test"), + }, + }, }) }) @@ -141,36 +127,22 @@ func TestAccGithubReleaseResource(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_release.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importReleaseByResourcePaths( - "github_repository.test", "github_release.test"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_release.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importReleaseByResourcePaths( + "github_repository.test", "github_release.test"), + }, + }, }) }) } diff --git a/github/resource_github_repository_autolink_reference_test.go b/github/resource_github_repository_autolink_reference_test.go index 0afa69392c..7151cf8be6 100644 --- a/github/resource_github_repository_autolink_reference_test.go +++ b/github/resource_github_repository_autolink_reference_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubRepositoryAutolinkReference(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates repository autolink reference without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "test-%s" @@ -93,33 +92,20 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports repository autolink reference without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "test-%s" @@ -200,61 +186,48 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - // autolink_default - { - ResourceName: "github_repository_autolink_reference.autolink_default", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), - }, - // autolink_alphanumeric - { - ResourceName: "github_repository_autolink_reference.autolink_alphanumeric", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), - }, - // autolink_numeric - { - ResourceName: "github_repository_autolink_reference.autolink_numeric", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), - }, - // autolink_with_port - { - ResourceName: "github_repository_autolink_reference.autolink_with_port", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + // autolink_default + { + ResourceName: "github_repository_autolink_reference.autolink_default", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), + }, + // autolink_alphanumeric + { + ResourceName: "github_repository_autolink_reference.autolink_alphanumeric", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), + }, + // autolink_numeric + { + ResourceName: "github_repository_autolink_reference.autolink_numeric", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), + }, + // autolink_with_port + { + ResourceName: "github_repository_autolink_reference.autolink_with_port", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), + }, + }, }) }) t.Run("imports repository autolink reference by key prefix without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "oof" { name = "oof-%s" @@ -269,44 +242,31 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - ResourceName: "github_repository_autolink_reference.autolink", - ImportState: true, - ImportStateVerify: true, - ImportStateId: fmt.Sprintf("oof-%s/OOF-", randomID), - }, - { - ResourceName: "github_repository_autolink_reference.autolink", - ImportState: true, - ImportStateId: fmt.Sprintf("oof-%s/OCTOCAT-", randomID), - ExpectError: regexp.MustCompile(`cannot find autolink reference`), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_repository_autolink_reference.autolink", + ImportState: true, + ImportStateVerify: true, + ImportStateId: fmt.Sprintf("oof-%s/OOF-", randomID), + }, + { + ResourceName: "github_repository_autolink_reference.autolink", + ImportState: true, + ImportStateId: fmt.Sprintf("oof-%s/OCTOCAT-", randomID), + ExpectError: regexp.MustCompile(`cannot find autolink reference`), + }, + }, }) }) t.Run("deletes repository autolink reference without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "test-%s" @@ -321,29 +281,15 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Destroy: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Destroy: true, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_collaborator_test.go b/github/resource_github_repository_collaborator_test.go index 190ecac68e..1b55fab83a 100644 --- a/github/resource_github_repository_collaborator_test.go +++ b/github/resource_github_repository_collaborator_test.go @@ -10,11 +10,12 @@ import ( ) func TestAccGithubRepositoryCollaborator(t *testing.T) { - t.Skip("update below to unskip this test run") - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") + } t.Run("creates invitations without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -23,10 +24,10 @@ func TestAccGithubRepositoryCollaborator(t *testing.T) { resource "github_repository_collaborator" "test_repo_collaborator" { repository = "${github_repository.test.name}" - username = "" + username = "%s" permission = "triage" } - `, randomID) + `, randomID, testAccConf.testExternalUser) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -35,39 +36,20 @@ func TestAccGithubRepositoryCollaborator(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates invitations when repository contains the org name", func(t *testing.T) { - orgName := os.Getenv("GITHUB_ORGANIZATION") - - if orgName == "" { - t.Skip("Set GITHUB_ORGANIZATION to unskip this test run") - } - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) configWithOwner := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -79,7 +61,7 @@ func TestAccGithubRepositoryCollaborator(t *testing.T) { username = "" permission = "triage" } - `, randomID, orgName) + `, randomID, testAccConf.owner) checkWithOwner := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -88,29 +70,15 @@ func TestAccGithubRepositoryCollaborator(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configWithOwner, - Check: checkWithOwner, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configWithOwner, + Check: checkWithOwner, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } @@ -154,10 +122,10 @@ func TestAccGithubRepositoryCollaboratorArchivedRepo(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("can delete collaborators from archived repositories without error", func(t *testing.T) { - // Note: This test requires GITHUB_TEST_COLLABORATOR to be set to a valid GitHub username - testCollaborator := os.Getenv("GITHUB_TEST_COLLABORATOR") + // Note: This test requires GH_TEST_COLLABORATOR to be set to a valid GitHub username + testCollaborator := os.Getenv("GH_TEST_COLLABORATOR") if testCollaborator == "" { - t.Skip("GITHUB_TEST_COLLABORATOR not set, skipping archived repository collaborator test") + t.Skip("GH_TEST_COLLABORATOR not set, skipping archived repository collaborator test") } config := fmt.Sprintf(` @@ -187,54 +155,44 @@ func TestAccGithubRepositoryCollaboratorArchivedRepo(t *testing.T) { } `, randomID, testCollaborator) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_collaborator.test", "username", - testCollaborator, - ), - resource.TestCheckResourceAttr( - "github_repository_collaborator.test", "permission", - "pull", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_collaborator.test", "username", + testCollaborator, ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + resource.TestCheckResourceAttr( + "github_repository_collaborator.test", "permission", + "pull", ), - }, - // This step should succeed - the collaborator should be removed from state - // without trying to actually delete it from the archived repo - { - Config: fmt.Sprintf(` + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", + ), + ), + }, + // This step should succeed - the collaborator should be removed from state + // without trying to actually delete it from the archived repo + { + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-collab-archive-%s" auto_init = true archived = true } `, randomID), - }, }, - }) - } - - t.Run("with individual mode", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with organization mode", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_collaborators_test.go b/github/resource_github_repository_collaborators_test.go index 61d52aa548..7eff96ecc2 100644 --- a/github/resource_github_repository_collaborators_test.go +++ b/github/resource_github_repository_collaborators_test.go @@ -1,9 +1,7 @@ package github import ( - "context" "fmt" - "os" "strings" "testing" @@ -14,30 +12,22 @@ import ( ) func TestAccGithubRepositoryCollaborators(t *testing.T) { - inOrgUser := os.Getenv("GITHUB_IN_ORG_USER") - inOrgUser2 := os.Getenv("GITHUB_IN_ORG_USER2") + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") + } - config := Config{BaseURL: "https://api.github.com/", Owner: testOwnerFunc(), Token: testToken} - meta, err := config.Meta() + ctx := t.Context() + meta, err := getTestMeta() if err != nil { - t.Fatalf("failed to return meta without error: %s", err.Error()) + t.Fatal(err) } - t.Run("creates collaborators without error", func(t *testing.T) { - if inOrgUser == "" { - t.Skip("set inOrgUser to unskip this test run") - } - - if inOrgUser == testOwnerFunc() { - t.Skip("inOrgUser can't be same as owner") - } - + t.Run("adds user collaborator", func(t *testing.T) { + conn := meta.v3client randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - conn := meta.(*Owner).v3client repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - teamName := fmt.Sprintf("tf-acc-test-team-%s", randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -52,9 +42,62 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "push" } } - `, repoName, inOrgUser) + `, repoName, testAccConf.testExternalUser) - orgConfig := fmt.Sprintf(` + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "0"), + func(state *terraform.State) error { + owner := testAccConf.owner + + collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary + for name, val := range collaborators.Attributes { + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != testAccConf.testExternalUser { + return fmt.Errorf("expected user.*.username to be set to %s, was %s", testAccConf.testExternalUser, val) + } + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "push" { + return fmt.Errorf("expected user.*.permission to be set to push, was %s", val) + } + } + + invites, _, err := conn.Repositories.ListInvitations(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(invites) != 1 { + return fmt.Errorf("expected an invite for %s but not found", testAccConf.testExternalUser) + } + if invites[0].GetInvitee().GetLogin() != testAccConf.testExternalUser { + return fmt.Errorf("expected an invite for %s for repo %s/%s", testAccConf.testExternalUser, owner, repoName) + } + perm := invites[0].GetPermissions() + if perm != "write" { + return fmt.Errorf("expected the invite for %s to have push perms for for %s/%s, found %s", testAccConf.testExternalUser, owner, repoName, perm) + } + return nil + }, + ), + }, + }, + }) + }) + + t.Run("adds team collaborator", func(t *testing.T) { + ctx := t.Context() + conn := meta.v3client + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-%s", randomID) + teamName := fmt.Sprintf("tf-acc-test-team-%s", randomID) + + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -72,139 +115,85 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { username = "%s" permission = "admin" } + team { team_id = github_team.test.id permission = "pull" } } - `, repoName, teamName, inOrgUser) - - testCase := func(t *testing.T, mode, config string, testCheck func(state *terraform.State) error) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: testCheck, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "0"), - func(state *terraform.State) error { - owner := meta.(*Owner).name - - collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary - for name, val := range collaborators.Attributes { - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != inOrgUser { - return fmt.Errorf("expected user.*.username to be set to %s, was %s", inOrgUser, val) - } - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "push" { - return fmt.Errorf("expected user.*.permission to be set to push, was %s", val) - } - } - - invites, _, err := conn.Repositories.ListInvitations(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(invites) != 1 { - return fmt.Errorf("expected an invite for %s but not found", inOrgUser) - } - if invites[0].GetInvitee().GetLogin() != inOrgUser { - return fmt.Errorf("expected an invite for %s for repo %s/%s", inOrgUser, owner, repoName) - } - perm := invites[0].GetPermissions() - if perm != "write" { - return fmt.Errorf("expected the invite for %s to have push perms for for %s/%s, found %s", inOrgUser, owner, repoName, perm) - } - return nil - }, - ) - testCase(t, individual, individualConfig, check) - }) + `, repoName, teamName, testAccConf.testExternalUser) - t.Run("with an organization account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "1"), - func(state *terraform.State) error { - owner := testOrganizationFunc() - - teamAttrs := state.RootModule().Resources["github_team.test"].Primary.Attributes - collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary - for name, val := range collaborators.Attributes { - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != inOrgUser { - return fmt.Errorf("expected user.*.username to be set to %s, was %s", inOrgUser, val) - } - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "admin" { - return fmt.Errorf("expected user.*.permission to be set to admin, was %s", val) - } - if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".team_id") && val != teamAttrs["id"] { - return fmt.Errorf("expected team.*.team_id to be set to %s, was %s", teamAttrs["id"], val) - } - if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".permission") && val != "pull" { - return fmt.Errorf("expected team.*.permission to be set to pull, was %s", val) - } - } - users, _, err := conn.Repositories.ListCollaborators(context.TODO(), owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) - if err != nil { - return err - } - if len(users) != 1 { - return fmt.Errorf("expected %s to be a collaborator for repo %s/%s", inOrgUser, owner, repoName) - } - perm := getPermission(users[0].GetRoleName()) - if perm != "admin" { - return fmt.Errorf("expected %s to have admin perms for repo %s/%s, found %s", inOrgUser, owner, repoName, perm) - } - teams, _, err := conn.Repositories.ListTeams(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(teams) != 1 { - return fmt.Errorf("expected team %s to be a collaborator for %s/%s", repoName, owner, repoName) - } - perm = getPermission(teams[0].GetPermission()) - if perm != "pull" { - return fmt.Errorf("expected team %s to have pull perms for repo %s/%s, found %s", repoName, owner, repoName, perm) - } - return nil + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "1"), + func(state *terraform.State) error { + owner := testAccConf.owner + + teamAttrs := state.RootModule().Resources["github_team.test"].Primary.Attributes + collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary + for name, val := range collaborators.Attributes { + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != testAccConf.testExternalUser { + return fmt.Errorf("expected user.*.username to be set to %s, was %s", testAccConf.testExternalUser, val) + } + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "admin" { + return fmt.Errorf("expected user.*.permission to be set to admin, was %s", val) + } + if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".team_id") && val != teamAttrs["id"] { + return fmt.Errorf("expected team.*.team_id to be set to %s, was %s", teamAttrs["id"], val) + } + if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".permission") && val != "pull" { + return fmt.Errorf("expected team.*.permission to be set to pull, was %s", val) + } + } + users, _, err := conn.Repositories.ListCollaborators(ctx, owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) + if err != nil { + return err + } + if len(users) != 1 { + return fmt.Errorf("expected %s to be a collaborator for repo %s/%s", testAccConf.testExternalUser, owner, repoName) + } + perm := getPermission(users[0].GetRoleName()) + if perm != "admin" { + return fmt.Errorf("expected %s to have admin perms for repo %s/%s, found %s", testAccConf.testExternalUser, owner, repoName, perm) + } + teams, _, err := conn.Repositories.ListTeams(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(teams) != 1 { + return fmt.Errorf("expected team %s to be a collaborator for %s/%s", repoName, owner, repoName) + } + perm = getPermission(teams[0].GetPermission()) + if perm != "pull" { + return fmt.Errorf("expected team %s to have pull perms for repo %s/%s, found %s", repoName, owner, repoName, perm) + } + return nil + }, + ), }, - ) - testCase(t, organization, orgConfig, check) + }, }) }) - t.Run("updates collaborators without error", func(t *testing.T) { - if inOrgUser == "" || inOrgUser2 == "" { - t.Skip("set inOrgUser and inOrgUser2 to unskip this test run") - } - - if inOrgUser == testOwnerFunc() || inOrgUser2 == testOwnerFunc() { - t.Skip("inOrgUser or inOrgUser2 can't be same as owner") + t.Run("updates user collaborators without error", func(t *testing.T) { + if len(testAccConf.testExternalUser2) == 0 { + t.Skip("No additional external user provided") } + ctx := t.Context() + conn := meta.v3client randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - conn := meta.(*Owner).v3client repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - team0Name := fmt.Sprintf("tf-acc-test-team-0-%s", randomID) - team1Name := fmt.Sprintf("tf-acc-test-team-1-%s", randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -219,9 +208,9 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "push" } } - `, repoName, inOrgUser) + `, repoName, testAccConf.testExternalUser) - individualConfigUpdate := fmt.Sprintf(` + configUpdate := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -236,9 +225,70 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "pull" } } - `, repoName, inOrgUser2) + `, repoName, testAccConf.testExternalUser2) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "0"), + func(state *terraform.State) error { + owner := testAccConf.owner + + collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary + for name, val := range collaborators.Attributes { + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != testAccConf.testExternalUser2 { + return fmt.Errorf("expected user.*.username to be set to %s, was %s", testAccConf.testExternalUser, val) + } + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "pull" { + return fmt.Errorf("expected user.*.permission to be set to pull, was %s", val) + } + } + + invites, _, err := conn.Repositories.ListInvitations(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(invites) != 1 { + return fmt.Errorf("expected an invite for %s but not found", testAccConf.testExternalUser) + } + if invites[0].GetInvitee().GetLogin() != testAccConf.testExternalUser2 { + return fmt.Errorf("expected an invite for %s for repo %s/%s", testAccConf.testExternalUser, owner, repoName) + } + perm := getPermission(invites[0].GetPermissions()) + if perm != "pull" { + return fmt.Errorf("expected the invite for %s to have pull perms for for %s/%s, found %s", testAccConf.testExternalUser, owner, repoName, perm) + } + return nil + }, + ), + }, + }, + }) + }) + + t.Run("updates team collaborators without error", func(t *testing.T) { + if len(testAccConf.testExternalUser2) == 0 { + t.Skip("No additional external user provided") + } - orgConfig := fmt.Sprintf(` + ctx := t.Context() + conn := meta.v3client + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-%s", randomID) + teamName1 := fmt.Sprintf("tf-acc-test-team-1-%s", randomID) + teamName2 := fmt.Sprintf("tf-acc-test-team-2-%s", randomID) + + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -273,9 +323,9 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "pull" } } - `, repoName, team0Name, team1Name, inOrgUser, inOrgUser2) + `, repoName, teamName1, teamName2, testAccConf.testExternalUser, testAccConf.testExternalUser2) - orgConfigUpdate := fmt.Sprintf(` + configUpdate := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -302,135 +352,79 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "push" } } - `, repoName, team0Name, team1Name, inOrgUser) - - testCase := func(t *testing.T, mode, config, configUpdate string, testCheck func(state *terraform.State) error) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: configUpdate, - Check: testCheck, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + `, repoName, teamName1, teamName2, testAccConf.testExternalUser) - t.Run("with an individual account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), - func(state *terraform.State) error { - owner := meta.(*Owner).name - - collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary - for name, val := range collaborators.Attributes { - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != inOrgUser2 { - return fmt.Errorf("expected user.*.username to be set to %s, was %s", inOrgUser, val) - } - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "pull" { - return fmt.Errorf("expected user.*.permission to be set to pull, was %s", val) - } - } - - invites, _, err := conn.Repositories.ListInvitations(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(invites) != 1 { - return fmt.Errorf("expected an invite for %s but not found", inOrgUser) - } - if invites[0].GetInvitee().GetLogin() != inOrgUser2 { - return fmt.Errorf("expected an invite for %s for repo %s/%s", inOrgUser, owner, repoName) - } - perm := getPermission(invites[0].GetPermissions()) - if perm != "pull" { - return fmt.Errorf("expected the invite for %s to have pull perms for for %s/%s, found %s", inOrgUser, owner, repoName, perm) - } - return nil + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, }, - ) - testCase(t, individual, individualConfig, individualConfigUpdate, check) - }) - - t.Run("with an organization account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "1"), - func(state *terraform.State) error { - owner := testOrganizationFunc() - - teamAttrs := state.RootModule().Resources["github_team.test_0"].Primary.Attributes - collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary - for name, val := range collaborators.Attributes { - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != inOrgUser { - return fmt.Errorf("expected user.*.username to be set to %s, was %s", inOrgUser, val) - } - if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "push" { - return fmt.Errorf("expected user.*.permission to be set to push, was %s", val) - } - if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".team_id") && val != teamAttrs["id"] { - return fmt.Errorf("expected team.*.team_id to be set to %s, was %s", teamAttrs["id"], val) - } - if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".permission") && val != "push" { - return fmt.Errorf("expected team.*.permission to be set to push, was %s", val) - } - } - - users, _, err := conn.Repositories.ListCollaborators(context.TODO(), owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) - if err != nil { - return err - } - if len(users) != 1 { - return fmt.Errorf("expected %s to be a collaborator for repo %s/%s", inOrgUser, owner, repoName) - } - perm := getPermission(users[0].GetRoleName()) - if perm != "push" { - return fmt.Errorf("expected %s to have push perms for repo %s/%s, found %s", inOrgUser, owner, repoName, perm) - } - teams, _, err := conn.Repositories.ListTeams(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(teams) != 1 { - return fmt.Errorf("expected team %s to be a collaborator for %s/%s", repoName, owner, repoName) - } - perm = getPermission(teams[0].GetPermission()) - if perm != "push" { - return fmt.Errorf("expected team %s to have push perms for repo %s/%s, found %s", repoName, owner, repoName, perm) - } - return nil + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "user.#"), + resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "user.#", "1"), + resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "1"), + func(state *terraform.State) error { + owner := testAccConf.owner + + teamAttrs := state.RootModule().Resources["github_team.test"].Primary.Attributes + collaborators := state.RootModule().Resources["github_repository_collaborators.test_repo_collaborators"].Primary + for name, val := range collaborators.Attributes { + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".username") && val != testAccConf.testExternalUser { + return fmt.Errorf("expected user.*.username to be set to %s, was %s", testAccConf.testExternalUser, val) + } + if strings.HasPrefix(name, "user.") && strings.HasSuffix(name, ".permission") && val != "push" { + return fmt.Errorf("expected user.*.permission to be set to push, was %s", val) + } + if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".team_id") && val != teamAttrs["id"] { + return fmt.Errorf("expected team.*.team_id to be set to %s, was %s", teamAttrs["id"], val) + } + if strings.HasPrefix(name, "team.") && strings.HasSuffix(name, ".permission") && val != "push" { + return fmt.Errorf("expected team.*.permission to be set to push, was %s", val) + } + } + + users, _, err := conn.Repositories.ListCollaborators(ctx, owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) + if err != nil { + return err + } + if len(users) != 1 { + return fmt.Errorf("expected %s to be a collaborator for repo %s/%s", testAccConf.testExternalUser, owner, repoName) + } + perm := getPermission(users[0].GetRoleName()) + if perm != "push" { + return fmt.Errorf("expected %s to have push perms for repo %s/%s, found %s", testAccConf.testExternalUser, owner, repoName, perm) + } + teams, _, err := conn.Repositories.ListTeams(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(teams) != 1 { + return fmt.Errorf("expected team %s to be a collaborator for %s/%s", repoName, owner, repoName) + } + perm = getPermission(teams[0].GetPermission()) + if perm != "push" { + return fmt.Errorf("expected team %s to have push perms for repo %s/%s, found %s", repoName, owner, repoName, perm) + } + return nil + }, + ), }, - ) - testCase(t, organization, orgConfig, orgConfigUpdate, check) + }, }) }) - t.Run("removes collaborators without error", func(t *testing.T) { - if inOrgUser == "" || inOrgUser2 == "" { - t.Skip("set inOrgUser and inOrgUser2 to unskip this test run") - } - - if inOrgUser == testOwnerFunc() || inOrgUser2 == testOwnerFunc() { - t.Skip("inOrgUser or inOrgUser2 can't be same as owner") - } - + t.Run("removes user collaborators without error", func(t *testing.T) { + ctx := t.Context() + conn := meta.v3client randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - conn := meta.(*Owner).v3client repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - teamName := fmt.Sprintf("tf-acc-test-team-%s", randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -445,9 +439,9 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "push" } } - `, repoName, inOrgUser) + `, repoName, testAccConf.testExternalUser) - individualConfigUpdate := fmt.Sprintf(` + configUpdate := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -455,7 +449,46 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { } `, repoName) - orgConfig := fmt.Sprintf(` + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + }, + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + func(state *terraform.State) error { + owner := testAccConf.owner + + invites, _, err := conn.Repositories.ListInvitations(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(invites) != 0 { + return fmt.Errorf("expected no invites but not found %d", len(invites)) + } + return nil + }, + ), + }, + }, + }) + }) + + t.Run("removes team collaborators without error", func(t *testing.T) { + if len(testAccConf.testExternalUser2) == 0 { + t.Skip("No additional external user provided") + } + + ctx := t.Context() + conn := meta.v3client + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-%s", randomID) + teamName := fmt.Sprintf("tf-acc-test-team-%s", randomID) + + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -482,9 +515,9 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "pull" } } - `, repoName, teamName, inOrgUser, inOrgUser2) + `, repoName, teamName, testAccConf.testExternalUser, testAccConf.testExternalUser2) - orgConfigUpdate := fmt.Sprintf(` + configUpdate := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -496,180 +529,37 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { } `, repoName, teamName) - testCase := func(t *testing.T, mode, config, configUpdate string, testCheck func(state *terraform.State) error) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - }, - { - Config: configUpdate, - Check: testCheck, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - func(state *terraform.State) error { - owner := meta.(*Owner).name - - invites, _, err := conn.Repositories.ListInvitations(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(invites) != 0 { - return fmt.Errorf("expected no invites but not found %d", len(invites)) - } - return nil - }, - ) - testCase(t, individual, individualConfig, individualConfigUpdate, check) - }) - - t.Run("with an organization account", func(t *testing.T) { - check := resource.ComposeTestCheckFunc( - func(state *terraform.State) error { - owner := testOrganizationFunc() - - users, _, err := conn.Repositories.ListCollaborators(context.TODO(), owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) - if err != nil { - return err - } - if len(users) != 0 { - return fmt.Errorf("expected no collaborators for repo %s/%s but found %d", owner, repoName, len(users)) - } - teams, _, err := conn.Repositories.ListTeams(context.TODO(), owner, repoName, nil) - if err != nil { - return err - } - if len(teams) != 0 { - return fmt.Errorf("expected no teams to be a collaborator for %s/%s but found %d", owner, repoName, len(teams)) - } - return nil - }, - ) - testCase(t, organization, orgConfig, orgConfigUpdate, check) - }) - }) - - t.Run("does not churn on team slug", func(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - team0Name := fmt.Sprintf("tf-acc-test-team-0-%s", randomID) - team1Name := fmt.Sprintf("tf-acc-test-team-1-%s", randomID) - - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "%s" - auto_init = true - visibility = "private" - } - - resource "github_team" "test_0" { - name = "%s" - } - - resource "github_team" "test_1" { - name = "%s" - } - - resource "github_repository_collaborators" "test_repo_collaborators" { - repository = "${github_repository.test.name}" - - team { - team_id = github_team.test_0.id - permission = "pull" - } - - team { - team_id = github_team.test_1.name - permission = "pull" - } - } - `, repoName, team0Name, team1Name) - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, - Providers: testAccProviders, + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, Steps: []resource.TestStep{ { Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "2"), - ), - }, - { - Config: config, - ExpectNonEmptyPlan: false, }, - }, - }) - }) - - t.Run("ignores specified teams", func(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - team0Name := fmt.Sprintf("tf-acc-test-team-0-%s", randomID) - team1Name := fmt.Sprintf("tf-acc-test-team-1-%s", randomID) - - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "%s" - auto_init = true - visibility = "private" - } - - resource "github_team" "test_0" { - name = "%s" - } - - resource "github_team_repository" "some_team_repo" { - team_id = github_team.test_0.id - repository = github_repository.test.name - } - - resource "github_team" "test_1" { - name = "%s" - } - - resource "github_repository_collaborators" "test_repo_collaborators" { - repository = "${github_repository.test.name}" - - team { - team_id = github_team.test_1.id - permission = "pull" - } - - ignore_team { - team_id = github_team.test_0.id - } - } - `, repoName, team0Name, team1Name) - - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ { - Config: config, + Config: configUpdate, Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttrSet("github_repository_collaborators.test_repo_collaborators", "team.#"), - resource.TestCheckResourceAttr("github_repository_collaborators.test_repo_collaborators", "team.#", "1"), + func(state *terraform.State) error { + owner := testAccConf.owner + + users, _, err := conn.Repositories.ListCollaborators(ctx, owner, repoName, &github.ListCollaboratorsOptions{Affiliation: "direct"}) + if err != nil { + return err + } + if len(users) != 0 { + return fmt.Errorf("expected no collaborators for repo %s/%s but found %d", owner, repoName, len(users)) + } + teams, _, err := conn.Repositories.ListTeams(ctx, owner, repoName, nil) + if err != nil { + return err + } + if len(teams) != 0 { + return fmt.Errorf("expected no teams to be a collaborator for %s/%s but found %d", owner, repoName, len(teams)) + } + return nil + }, ), }, - { - Config: config, - ExpectNonEmptyPlan: false, - }, }, }) }) diff --git a/github/resource_github_repository_custom_property_test.go b/github/resource_github_repository_custom_property_test.go index e6d8132ef6..7b8a4deae7 100644 --- a/github/resource_github_repository_custom_property_test.go +++ b/github/resource_github_repository_custom_property_test.go @@ -9,196 +9,166 @@ import ( ) func TestAccGithubRepositoryCustomProperty(t *testing.T) { - t.Skip("You need an org with custom properties already setup as described in the variables below") // TODO: at the time of writing org_custom_properties are not supported by this terraform provider, so cant be setup in the test itself for now - singleSelectPropertyName := "single-select" // Needs to be a of type single_select, and have "option1" as an option - multiSelectPropertyName := "multi-select" // Needs to be a of type multi_select, and have "option1" and "option2" as an options - trueFlasePropertyName := "true-false" // Needs to be a of type true_false - stringPropertyName := "string" // Needs to be a of type string - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates custom property of type single_select without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + allowed_values = ["option1", "option2"] + description = "Test Description" + property_name = "%s" + value_type = "single_select" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "single_select" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["option1"] } - `, randomID, singleSelectPropertyName) + `, propertyName, randomID) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", singleSelectPropertyName), + resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", propertyName), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.#", "1"), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.0", "option1"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type multi_select without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + allowed_values = ["option1", "option2"] + description = "Test Description" + property_name = "%s" + value_type = "multi_select" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "multi_select" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["option1", "option2"] } - `, randomID, multiSelectPropertyName) + `, propertyName, randomID) checkWithOwner := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", multiSelectPropertyName), + resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", propertyName), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.#", "2"), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.0", "option1"), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.1", "option2"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checkWithOwner, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checkWithOwner, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type true-false without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + description = "Test Description" + property_name = "%s" + value_type = "true_false" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "true_false" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["true"] } - `, randomID, trueFlasePropertyName) + `, propertyName, randomID) checkWithOwner := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", trueFlasePropertyName), + resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", propertyName), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.#", "1"), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.0", "true"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checkWithOwner, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checkWithOwner, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates custom property of type string without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + propertyName := fmt.Sprintf("tf-acc-test-property-%s", randomID) + config := fmt.Sprintf(` + resource "github_organization_custom_properties" "test" { + description = "Test Description" + property_name = "%s" + value_type = "string" + } resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true } resource "github_repository_custom_property" "test" { repository = github_repository.test.name - property_name = "%s" - property_type = "string" + property_name = github_organization_custom_properties.test.property_name + property_type = github_organization_custom_properties.test.value_type property_value = ["text"] } - `, randomID, stringPropertyName) + `, propertyName, randomID) checkWithOwner := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", stringPropertyName), + resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_name", propertyName), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.#", "1"), resource.TestCheckResourceAttr("github_repository_custom_property.test", "property_value.0", "text"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checkWithOwner, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checkWithOwner, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_automated_security_fixes.go b/github/resource_github_repository_dependabot_security_updates.go similarity index 100% rename from github/resource_github_repository_automated_security_fixes.go rename to github/resource_github_repository_dependabot_security_updates.go diff --git a/github/resource_github_repository_automated_security_fixes_test.go b/github/resource_github_repository_dependabot_security_updates_test.go similarity index 54% rename from github/resource_github_repository_automated_security_fixes_test.go rename to github/resource_github_repository_dependabot_security_updates_test.go index 04b6081255..7308473b97 100644 --- a/github/resource_github_repository_automated_security_fixes_test.go +++ b/github/resource_github_repository_dependabot_security_updates_test.go @@ -9,10 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestAccGithubAutomatedSecurityFixes(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - +func TestAccGithubRepositoryDependabotSecurityUpdates(t *testing.T) { t.Run("enables automated security fixes without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) enabled := "enabled = false" updatedEnabled := "enabled = true" config := fmt.Sprintf(` @@ -46,39 +45,26 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - enabled, - updatedEnabled, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + enabled, + updatedEnabled, 1), + Check: checks["after"], + }, + }, }) }) t.Run("disables automated security fixes without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) enabled := "enabled = true" updatedEnabled := "enabled = false" @@ -113,39 +99,26 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - enabled, - updatedEnabled, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + enabled, + updatedEnabled, 1), + Check: checks["after"], + }, + }, }) }) t.Run("imports automated security fixes without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -164,34 +137,20 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { resource.TestCheckResourceAttr("github_repository_dependabot_security_updates.test", "enabled", "false"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_repository_dependabot_security_updates.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_repository_dependabot_security_updates.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_repository_deploy_key_test.go b/github/resource_github_repository_deploy_key_test.go index 21754c3da7..f89e396e0a 100644 --- a/github/resource_github_repository_deploy_key_test.go +++ b/github/resource_github_repository_deploy_key_test.go @@ -3,11 +3,11 @@ package github import ( "context" "fmt" - "os" "os/exec" "path/filepath" "regexp" "strconv" + "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -52,53 +52,52 @@ func TestSuppressDeployKeyDiff(t *testing.T) { } func TestAccGithubRepositoryDeployKey_basic(t *testing.T) { - testUserEmail := os.Getenv("GITHUB_TEST_USER_EMAIL") - if testUserEmail == "" { - t.Skip("Skipping because `GITHUB_TEST_USER_EMAIL` is not set") - } - cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -t rsa -b 4096 -C %s -N '' -f test-fixtures/id_rsa>/dev/null <<< y >/dev/null", testUserEmail)) - if err := cmd.Run(); err != nil { - t.Fatal(err) - } + t.Run("creates repository deploy key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + keyName := fmt.Sprintf("%s_rsa", randomID) + cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -t rsa -b 4096 -C test@example.com -N '' -f test-fixtures/%s>/dev/null <<< y >/dev/null", keyName)) + if err := cmd.Run(); err != nil { + t.Fatal(err) + } - rn := "github_repository_deploy_key.test_repo_deploy_key" - rs := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - repositoryName := fmt.Sprintf("acctest-%s", rs) - keyPath := filepath.Join("test-fixtures", "id_rsa.pub") - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubRepositoryDeployKeyDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubRepositoryDeployKeyConfig(repositoryName, keyPath), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubRepositoryDeployKeyExists(rn), - resource.TestCheckResourceAttr(rn, "read_only", "false"), - resource.TestCheckResourceAttr(rn, "repository", repositoryName), - resource.TestMatchResourceAttr(rn, "key", regexp.MustCompile(`^ssh-rsa [^\s]+$`)), - resource.TestCheckResourceAttr(rn, "title", "title"), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + rn := "github_repository_deploy_key.test_repo_deploy_key" + rs := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + repositoryName := fmt.Sprintf("acctest-%s", rs) + keyPath := strings.ReplaceAll(filepath.Join("test-fixtures", fmt.Sprintf("%s.pub", keyName)), "\\", "/") + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubRepositoryDeployKeyDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubRepositoryDeployKeyConfig(repositoryName, keyPath), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubRepositoryDeployKeyExists(t.Context(), rn), + resource.TestCheckResourceAttr(rn, "read_only", "false"), + resource.TestCheckResourceAttr(rn, "repository", repositoryName), + resource.TestMatchResourceAttr(rn, "key", regexp.MustCompile(`^ssh-rsa [^\s]+$`)), + resource.TestCheckResourceAttr(rn, "title", "title"), + ), + }, }, - }, + }) }) } func testAccCheckGithubRepositoryDeployKeyDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client for _, rs := range s.RootModule().Resources { if rs.Type != "github_repository_deploy_key" { continue } - owner := testAccProvider.Meta().(*Owner).name + owner := meta.name repoName, idString, err := parseTwoPartID(rs.Primary.ID, "repository", "ID") if err != nil { return err @@ -109,7 +108,7 @@ func testAccCheckGithubRepositoryDeployKeyDestroy(s *terraform.State) error { return unconvertibleIdErr(idString, err) } - _, resp, err := conn.Repositories.GetKey(context.TODO(), owner, repoName, id) + _, resp, err := conn.Repositories.GetKey(context.Background(), owner, repoName, id) if err != nil && resp.StatusCode != 404 { return err @@ -120,7 +119,7 @@ func testAccCheckGithubRepositoryDeployKeyDestroy(s *terraform.State) error { return nil } -func testAccCheckGithubRepositoryDeployKeyExists(n string) resource.TestCheckFunc { +func testAccCheckGithubRepositoryDeployKeyExists(ctx context.Context, n string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -131,8 +130,12 @@ func testAccCheckGithubRepositoryDeployKeyExists(n string) resource.TestCheckFun return fmt.Errorf("no membership ID is set") } - conn := testAccProvider.Meta().(*Owner).v3client - owner := testAccProvider.Meta().(*Owner).name + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + owner := meta.name repoName, idString, err := parseTwoPartID(rs.Primary.ID, "repository", "ID") if err != nil { return err @@ -143,7 +146,7 @@ func testAccCheckGithubRepositoryDeployKeyExists(n string) resource.TestCheckFun return unconvertibleIdErr(idString, err) } - _, _, err = conn.Repositories.GetKey(context.TODO(), owner, repoName, id) + _, _, err = conn.Repositories.GetKey(ctx, owner, repoName, id) if err != nil { return err } @@ -159,20 +162,24 @@ resource "github_repository" "test_repo" { } resource "github_repository_deploy_key" "test_repo_deploy_key" { - key = "${file("%s")}" + key = file("%s") read_only = "false" - repository = "${github_repository.test_repo.name}" + repository = github_repository.test_repo.name title = "title" } `, name, keyPath) } func TestAccGithubRepositoryDeployKeyArchivedRepo(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("can delete deploy keys from archived repositories without error", func(t *testing.T) { - // Create a TEMP SSH key for testing only - key := `ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC+7E/lL5ZWD7TCnNHfQWfyZ+/g1J0+E2u5R1d8K3/WKXGmI4DXk5JHZv+/rj+1J5HL5+3rJ4Z5bGF4e1z8E9JqHzF+8lQ3EI8E3z+9CQ5E5SYPeZPLxFk= test@example.com` + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + keyName := fmt.Sprintf("%s_rsa", randomID) + cmd := exec.Command("bash", "-c", fmt.Sprintf("ssh-keygen -t rsa -b 4096 -C test@example.com -N '' -f test-fixtures/%s>/dev/null <<< y >/dev/null", keyName)) + if err := cmd.Run(); err != nil { + t.Fatal(err) + } + + keyPath := strings.ReplaceAll(filepath.Join("test-fixtures", fmt.Sprintf("%s.pub", keyName)), "\\", "/") config := fmt.Sprintf(` resource "github_repository" "test" { @@ -181,12 +188,12 @@ func TestAccGithubRepositoryDeployKeyArchivedRepo(t *testing.T) { } resource "github_repository_deploy_key" "test" { - key = "%s" + key = file("%s") read_only = true repository = github_repository.test.name title = "test-archived-deploy-key" } - `, randomID, key) + `, randomID, keyPath) archivedConfig := fmt.Sprintf(` resource "github_repository" "test" { @@ -196,55 +203,45 @@ func TestAccGithubRepositoryDeployKeyArchivedRepo(t *testing.T) { } resource "github_repository_deploy_key" "test" { - key = "%s" + key = file("%s") read_only = true repository = github_repository.test.name title = "test-archived-deploy-key" } - `, randomID, key) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_deploy_key.test", "title", - "test-archived-deploy-key", - ), + `, randomID, keyPath) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_deploy_key.test", "title", + "test-archived-deploy-key", ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", ), - }, - { - Config: fmt.Sprintf(` + ), + }, + { + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-deploy-key-archive-%s" auto_init = true archived = true } `, randomID), - }, }, - }) - } - - t.Run("with individual mode", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with organization mode", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_deployment_branch_policy_test.go b/github/resource_github_repository_deployment_branch_policy_test.go index 63ae954f08..bdbd013be2 100644 --- a/github/resource_github_repository_deployment_branch_policy_test.go +++ b/github/resource_github_repository_deployment_branch_policy_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubRepositoryDeploymentBranchPolicy(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates deployment branch policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -60,33 +59,19 @@ func TestAccGithubRepositoryDeploymentBranchPolicy(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config + config1, - Check: check1, - }, - { - Config: config + config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config + config1, + Check: check1, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config + config2, + Check: check2, + }, + }, }) }) } diff --git a/github/resource_github_repository_environment_deployment_policy_test.go b/github/resource_github_repository_environment_deployment_policy_test.go index 6c194b5e76..98c3910885 100644 --- a/github/resource_github_repository_environment_deployment_policy_test.go +++ b/github/resource_github_repository_environment_deployment_policy_test.go @@ -9,10 +9,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranch(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - +func TestAccGithubRepositoryEnvironmentDeploymentPolicy(t *testing.T) { t.Run("creates a repository environment with branch-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_user" "current" { @@ -63,37 +62,20 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranch(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("updates the pattern for a branch-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) var deploymentPolicyId string config1 := fmt.Sprintf(` @@ -201,41 +183,24 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config1, - Check: check1, - }, - { - Config: config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check2, + }, + }, }) }) -} - -func TestAccGithubRepositoryEnvironmentDeploymentPolicyTag(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("creates a repository environment with tag-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_user" "current" { @@ -286,38 +251,21 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTag(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("updates the pattern for a tag-based deployment policy", func(t *testing.T) { var deploymentPolicyId string + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config1 := fmt.Sprintf(` @@ -424,42 +372,25 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config1, - Check: check1, - }, - { - Config: config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check2, + }, + }, }) }) -} - -func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("recreates deployment policy when pattern type changes from branch to tag", func(t *testing.T) { var deploymentPolicyId string + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config1 := fmt.Sprintf(` @@ -566,42 +497,25 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *test ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config1, - Check: check1, - }, - { - Config: config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check2, + }, + }, }) }) -} - -func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("recreates deployment policy when pattern type changes from tag to branch", func(t *testing.T) { var deploymentPolicyId string + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config1 := fmt.Sprintf(` @@ -708,33 +622,19 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config1, - Check: check1, - }, - { - Config: config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check2, + }, + }, }) }) } diff --git a/github/resource_github_repository_environment_test.go b/github/resource_github_repository_environment_test.go index c14a29064d..addcfeb42d 100644 --- a/github/resource_github_repository_environment_test.go +++ b/github/resource_github_repository_environment_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubRepositoryEnvironment(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates a repository environment", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` data "github_user" "current" { @@ -47,29 +46,15 @@ func TestAccGithubRepositoryEnvironment(t *testing.T) { resource.TestCheckResourceAttr("github_repository_environment.test", "wait_timer", "10000"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_file.go b/github/resource_github_repository_file.go index 8a9c278cd9..83edad8f06 100644 --- a/github/resource_github_repository_file.go +++ b/github/resource_github_repository_file.go @@ -353,12 +353,12 @@ func resourceGithubRepositoryFileRead(d *schema.ResourceData, meta any) error { commit, _, err = client.Repositories.GetCommit(ctx, owner, repo, sha.(string), nil) } else { log.Printf("[DEBUG] Commit SHA unknown for file: %s/%s/%s, looking for commit...", owner, repo, file) - commit, err = getFileCommit(client, owner, repo, file, ref) - log.Printf("[DEBUG] Found file: %s/%s/%s, in commit SHA: %s ", owner, repo, file, commit.GetSHA()) + commit, err = getFileCommit(ctx, client, owner, repo, file, ref) } if err != nil { return err } + log.Printf("[DEBUG] Found file: %s/%s/%s, in commit SHA: %s ", owner, repo, file, commit.GetSHA()) if err = d.Set("commit_sha", commit.GetSHA()); err != nil { return err diff --git a/github/resource_github_repository_file_test.go b/github/resource_github_repository_file_test.go index 03603e5d86..8c389bf454 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -13,13 +13,13 @@ import ( func TestAccGithubRepositoryFile(t *testing.T) { t.Run("creates and manages files", func(t *testing.T) { config := fmt.Sprintf(` - + resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true vulnerability_alerts = true } - + resource "github_repository_file" "test" { repository = github_repository.test.name branch = "main" @@ -60,29 +60,15 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource.TestCheckNoResourceAttr("github_repository_file.test", "autocreate_branch_source_sha"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -91,7 +77,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true - vulnerability_alerts = true + vulnerability_alerts = true } resource "github_repository_file" "test" { @@ -133,35 +119,21 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource.TestCheckNoResourceAttr("github_repository_file.test", "autocreate_branch_source_sha"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`refusing to overwrite existing file`), - }, - { - Config: strings.Replace(config, - "overwrite_on_create = false", - "overwrite_on_create = true", 1), - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`refusing to overwrite existing file`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + "overwrite_on_create = false", + "overwrite_on_create = true", 1), + Check: check, + }, + }, }) }) @@ -174,19 +146,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { vulnerability_alerts = true } - resource "github_branch" "test" { - repository = github_repository.test.name - branch = "test" - } - - resource "github_branch_default" "default"{ - repository = github_repository.test.name - branch = github_branch.test.branch - } - resource "github_repository_file" "test" { - depends_on = [github_branch_default.default] - repository = github_repository.test.name file = "test" content = "bar" @@ -207,7 +167,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { ), resource.TestCheckResourceAttr( "github_repository_file.test", "ref", - "test", + "main", ), resource.TestCheckResourceAttrSet( "github_repository_file.test", "commit_author", @@ -226,29 +186,15 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource.TestCheckNoResourceAttr("github_repository_file.test", "autocreate_branch_source_sha"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -259,7 +205,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { auto_init = true vulnerability_alerts = true } - + resource "github_repository_file" "test" { repository = github_repository.test.name branch = "does/not/exist" @@ -302,35 +248,21 @@ func TestAccGithubRepositoryFile(t *testing.T) { resource.TestCheckResourceAttrSet("github_repository_file.test", "autocreate_branch_source_sha"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - ExpectError: regexp.MustCompile(`unexpected status code: 404 Not Found`), - }, - { - Config: strings.Replace(config, - "autocreate_branch = false", - "autocreate_branch = true", 1), - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile(`unexpected status code: 404 Not Found`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + "autocreate_branch = false", + "autocreate_branch = true", 1), + Check: check, + }, + }, }) }) @@ -357,50 +289,40 @@ func TestAccGithubRepositoryFile(t *testing.T) { `auto_init = true archived = true`, 1) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_file.test", "file", - "archived-test.md", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_file.test", "file", + "archived-test.md", ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", ), - }, - // This step should succeed - the file should be removed from state - // without trying to actually delete it from the archived repo - { - Config: fmt.Sprintf(` + ), + }, + // This step should succeed - the file should be removed from state + // without trying to actually delete it from the archived repo + { + Config: fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-file-archive-%s" auto_init = true archived = true } `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)), - }, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_milestone_test.go b/github/resource_github_repository_milestone_test.go index 8858124194..ebede46eed 100644 --- a/github/resource_github_repository_milestone_test.go +++ b/github/resource_github_repository_milestone_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubRepositoryMilestone(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates a repository milestone", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -36,29 +35,15 @@ func TestAccGithubRepositoryMilestone(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_project_test.go b/github/resource_github_repository_project_test.go index 4911660fec..3c77fc0122 100644 --- a/github/resource_github_repository_project_test.go +++ b/github/resource_github_repository_project_test.go @@ -10,11 +10,10 @@ import ( ) func TestAccGithubRepositoryProject(t *testing.T) { - t.Skip("Skipping test as the GitHub REST API no longer supports classic projects") - - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + t.Skip("Skipping test as the GitHub API no longer supports classic projects") t.Run("creates a repository project", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -36,29 +35,15 @@ func TestAccGithubRepositoryProject(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_repository_pull_request.go b/github/resource_github_repository_pull_request.go index 6c33eca154..75e69ce181 100644 --- a/github/resource_github_repository_pull_request.go +++ b/github/resource_github_repository_pull_request.go @@ -136,7 +136,7 @@ func resourceGithubRepositoryPullRequest() *schema.Resource { } func resourceGithubRepositoryPullRequestCreate(d *schema.ResourceData, meta any) error { - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client // For convenience, by default we expect that the base repository and head @@ -175,7 +175,7 @@ func resourceGithubRepositoryPullRequestCreate(d *schema.ResourceData, meta any) } func resourceGithubRepositoryPullRequestRead(d *schema.ResourceData, meta any) error { - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client owner, repository, number, err := parsePullRequestID(d) @@ -264,7 +264,7 @@ func resourceGithubRepositoryPullRequestRead(d *schema.ResourceData, meta any) e } func resourceGithubRepositoryPullRequestUpdate(d *schema.ResourceData, meta any) error { - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client owner, repository, number, err := parsePullRequestID(d) @@ -308,7 +308,7 @@ func resourceGithubRepositoryPullRequestDelete(d *schema.ResourceData, meta any) return nil } - ctx := context.TODO() + ctx := context.Background() client := meta.(*Owner).v3client owner, repository, number, err := parsePullRequestID(d) diff --git a/github/resource_github_repository_pull_request_test.go b/github/resource_github_repository_pull_request_test.go index c76a1a99f7..b1f964c7c5 100644 --- a/github/resource_github_repository_pull_request_test.go +++ b/github/resource_github_repository_pull_request_test.go @@ -63,34 +63,20 @@ func TestAccGithubRepositoryPullRequest(t *testing.T) { resource.TestCheckResourceAttrSet(resourceName, "updated_at"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_repository_ruleset.go b/github/resource_github_repository_ruleset.go index 3e711bd32d..03adb46567 100644 --- a/github/resource_github_repository_ruleset.go +++ b/github/resource_github_repository_ruleset.go @@ -710,7 +710,7 @@ func resourceGithubRepositoryRulesetUpdate(d *schema.ResourceData, meta any) err // UpdateRuleset uses `omitempty` on BypassActors, causing empty arrays to be omitted from the JSON. // UpdateRulesetNoBypassActor always includes the field so that bypass actors can actually be removed. // See: https://github.com/google/go-github/blob/b6248e6f6aec019e75ba2c8e189bfe89f36b7d01/github/repos_rules.go#L196 - if d.HasChange("bypass_actors") { + if d.HasChange("bypass_actors") && len(rulesetReq.BypassActors) == 0 { ruleset, _, err = client.Repositories.UpdateRulesetNoBypassActor(ctx, owner, repoName, rulesetID, rulesetReq) } else { ruleset, _, err = client.Repositories.UpdateRuleset(ctx, owner, repoName, rulesetID, rulesetReq) diff --git a/github/resource_github_repository_ruleset_test.go b/github/resource_github_repository_ruleset_test.go index ee5d3c1c28..a9466ee697 100644 --- a/github/resource_github_repository_ruleset_test.go +++ b/github/resource_github_repository_ruleset_test.go @@ -13,15 +13,15 @@ import ( ) func TestGithubRepositoryRulesets(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + t.Run("creates and updates repository rulesets without errors", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("Creates and updates repository rulesets without errors", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" auto_init = true default_branch = "main" - vulnerability_alerts = true + vulnerability_alerts = true } resource "github_repository_environment" "example" { @@ -125,40 +125,20 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("Creates and updates repository rulesets with enterprise features without errors", func(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - - if testEnterprise == "" { - t.Skip("Skipping because `ENTERPRISE_SLUG` is not set") - } + t.Run("creates and updates repository rulesets with enterprise features without errors", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -207,25 +187,20 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an enterprise account", func(t *testing.T) { - testCase(t, enterprise) + }, }) }) - t.Run("Updates a ruleset name without error", func(t *testing.T) { + t.Run("updates a ruleset name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) repoName := fmt.Sprintf(`tf-acc-test-rename-%[1]s`, randomID) oldRSName := fmt.Sprintf(`ruleset-%[1]s`, randomID) newRSName := fmt.Sprintf(`%[1]s-renamed`, randomID) @@ -264,41 +239,29 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - // Rename the ruleset to something else - Config: strings.Replace( - config, - oldRSName, - newRSName, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + // Rename the ruleset to something else + Config: strings.Replace( + config, + oldRSName, + newRSName, 1), + Check: checks["after"], + }, + }, }) }) - t.Run("Imports rulesets without error", func(t *testing.T) { + t.Run("imports rulesets without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-import-%[1]s" @@ -377,42 +340,28 @@ func TestGithubRepositoryRulesets(t *testing.T) { resource.TestCheckResourceAttrSet("github_repository_ruleset.test", "name"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_repository_ruleset.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdFunc: importRepositoryRulesetByResourcePaths( - "github_repository.test", "github_repository_ruleset.test"), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + { + ResourceName: "github_repository_ruleset.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importRepositoryRulesetByResourcePaths( + "github_repository.test", "github_repository_ruleset.test"), + }, + }, }) + }) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + t.Run("creates a push repository ruleset without errors", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) - t.Run("Creates a push repository ruleset without errors", func(t *testing.T) { - if isPaidPlan != "true" { - t.Skip("Skipping because `GITHUB_PAID_FEATURES` is not set to true") - } config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-%s" @@ -463,30 +412,21 @@ func TestGithubRepositoryRulesets(t *testing.T) { "*.zip", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasPaidOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - t.Run("with a paid plan in an organization", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("Creates repository ruleset with merge queue SQUASH method", func(t *testing.T) { + t.Run("creates repository ruleset with merge queue squash method", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-merge-queue-%s" @@ -532,33 +472,21 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("Removes bypass actors when removed from configuration", func(t *testing.T) { + t.Run("removes bypass actors when removed from configuration", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-bypass-%s" @@ -569,6 +497,13 @@ func TestGithubRepositoryRulesets(t *testing.T) { resource "github_team" "test" { name = "tf-acc-test-team-%[1]s" description = "Terraform acc test team" + privacy = "closed" + } + + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "push" } resource "github_repository_ruleset" "test" { @@ -578,7 +513,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { enforcement = "active" bypass_actors { - actor_id = github_team.test.id + actor_id = github_team_repository.test.team_id actor_type = "Team" bypass_mode = "pull_request" } @@ -602,69 +537,74 @@ func TestGithubRepositoryRulesets(t *testing.T) { } `, randomID) - configWithoutBypass := strings.Replace( - config, - `bypass_actors { - actor_id = github_team.test.id - actor_type = "Team" - bypass_mode = "pull_request" - } + configWithoutBypass := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-bypass-%s" + description = "Terraform acceptance tests %[1]s" + auto_init = true + } - `, - "", - 1, - ) + resource "github_team" "test" { + name = "tf-acc-test-team-%[1]s" + description = "Terraform acc test team" + privacy = "closed" + } - checks := map[string]resource.TestCheckFunc{ - "with_bypass": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.#", - "1", - ), - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.0.actor_type", - "Team", - ), - ), - "without_bypass": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.#", - "0", - ), - ), - } + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "push" + } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["with_bypass"], - }, - { - Config: configWithoutBypass, - Check: checks["without_bypass"], - }, - }, - }) - } + resource "github_repository_ruleset" "test" { + name = "test-bypass" + repository = github_repository.test.id + target = "branch" + enforcement = "active" - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + conditions { + ref_name { + include = ["~ALL"] + exclude = [] + } + } - t.Run("with an individual account", func(t *testing.T) { - t.Skip("bypass actors require organization resources") - }) + rules { + pull_request { + dismiss_stale_reviews_on_push = false + require_code_owner_review = true + require_last_push_approval = false + required_approving_review_count = 1 + required_review_thread_resolution = false + } + } + } + `, randomID) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository_ruleset.test", "bypass_actors.#", "1"), + resource.TestCheckResourceAttr("github_repository_ruleset.test", "bypass_actors.0.actor_type", "Team"), + ), + }, + { + Config: configWithoutBypass, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository_ruleset.test", "bypass_actors.#", "0"), + ), + }, + }, }) }) - t.Run("Updates ruleset without bypass actors defined", func(t *testing.T) { + t.Run("updates ruleset without bypass actors defined", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-no-bypass-%s" @@ -721,37 +661,25 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: configUpdated, - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: checks["after"], + }, + }, }) }) - t.Run("Creates repository ruleset with all bypass_modes", func(t *testing.T) { + t.Run("creates repository ruleset with all bypass_modes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-bypass-modes-%s" @@ -762,16 +690,39 @@ func TestGithubRepositoryRulesets(t *testing.T) { resource "github_team" "test_always" { name = "tf-acc-test-team-always-%[1]s" description = "Terraform acc test team for always bypass" + privacy = "closed" + } + + resource "github_team_repository" "test_always" { + team_id = github_team.test_always.id + repository = github_repository.test.name + permission = "push" } resource "github_team" "test_pull_request" { name = "tf-acc-test-team-pr-%[1]s" description = "Terraform acc test team for pull_request bypass" + privacy = "closed" + depends_on = [github_team.test_always] + } + + resource "github_team_repository" "test_pull_request" { + team_id = github_team.test_pull_request.id + repository = github_repository.test.name + permission = "push" } resource "github_team" "test_exempt" { name = "tf-acc-test-team-exempt-%[1]s" description = "Terraform acc test team for exempt bypass" + privacy = "closed" + depends_on = [github_team.test_pull_request] + } + + resource "github_team_repository" "test_exempt" { + team_id = github_team.test_exempt.id + repository = github_repository.test.name + permission = "push" } resource "github_repository_ruleset" "test" { @@ -781,19 +732,19 @@ func TestGithubRepositoryRulesets(t *testing.T) { enforcement = "active" bypass_actors { - actor_id = github_team.test_always.id + actor_id = github_team_repository.test_always.team_id actor_type = "Team" bypass_mode = "always" } bypass_actors { - actor_id = github_team.test_pull_request.id + actor_id = github_team_repository.test_pull_request.team_id actor_type = "Team" bypass_mode = "pull_request" } bypass_actors { - actor_id = github_team.test_exempt.id + actor_id = github_team_repository.test_exempt.team_id actor_type = "Team" bypass_mode = "exempt" } @@ -851,33 +802,21 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("bypass actors require organization resources") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("Updates bypass_mode without error", func(t *testing.T) { + t.Run("updates bypass_mode without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-bypass-update-%s" @@ -888,6 +827,13 @@ func TestGithubRepositoryRulesets(t *testing.T) { resource "github_team" "test" { name = "tf-acc-test-team-update-%[1]s" description = "Terraform acc test team" + privacy = "closed" + } + + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "push" } resource "github_repository_ruleset" "test" { @@ -897,7 +843,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { enforcement = "active" bypass_actors { - actor_id = github_team.test.id + actor_id = github_team_repository.test.team_id actor_type = "Team" bypass_mode = "always" } @@ -937,37 +883,25 @@ func TestGithubRepositoryRulesets(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: configUpdated, - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("bypass actors require organization resources") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: checks["after"], + }, + }, }) }) t.Run("Creates repository ruleset with different actor types and bypass modes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-actor-types-%s" @@ -978,6 +912,13 @@ func TestGithubRepositoryRulesets(t *testing.T) { resource "github_team" "test" { name = "tf-acc-test-team-actor-%[1]s" description = "Terraform acc test team" + privacy = "closed" + } + + resource "github_team_repository" "test" { + team_id = github_team.test.id + repository = github_repository.test.name + permission = "push" } resource "github_repository_ruleset" "test" { @@ -987,9 +928,9 @@ func TestGithubRepositoryRulesets(t *testing.T) { enforcement = "active" bypass_actors { - actor_id = github_team.test.id - actor_type = "Team" - bypass_mode = "always" + actor_id = 0 + actor_type = "OrganizationAdmin" + bypass_mode = "exempt" } bypass_actors { @@ -999,9 +940,9 @@ func TestGithubRepositoryRulesets(t *testing.T) { } bypass_actors { - actor_id = 1 - actor_type = "OrganizationAdmin" - bypass_mode = "exempt" + actor_id = github_team_repository.test.team_id + actor_type = "Team" + bypass_mode = "always" } conditions { @@ -1023,14 +964,14 @@ func TestGithubRepositoryRulesets(t *testing.T) { "3", ), resource.TestCheckResourceAttrSet( - "github_repository_ruleset.test", "bypass_actors.0.actor_id", + "github_repository_ruleset.test", "bypass_actors.2.actor_id", ), resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.0.actor_type", + "github_repository_ruleset.test", "bypass_actors.2.actor_type", "Team", ), resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.0.bypass_mode", + "github_repository_ruleset.test", "bypass_actors.2.bypass_mode", "always", ), resource.TestCheckResourceAttr( @@ -1046,42 +987,28 @@ func TestGithubRepositoryRulesets(t *testing.T) { "pull_request", ), resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.2.actor_id", - "1", + "github_repository_ruleset.test", "bypass_actors.0.actor_id", + "0", ), resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.2.actor_type", + "github_repository_ruleset.test", "bypass_actors.0.actor_type", "OrganizationAdmin", ), resource.TestCheckResourceAttr( - "github_repository_ruleset.test", "bypass_actors.2.bypass_mode", + "github_repository_ruleset.test", "bypass_actors.0.bypass_mode", "exempt", ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("bypass actors require organization resources") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } @@ -1096,6 +1023,7 @@ func TestGithubRepositoryRulesetArchived(t *testing.T) { auto_init = true archived = false } + resource "github_repository_ruleset" "test" { name = "test" repository = github_repository.test.name diff --git a/github/resource_github_repository_test.go b/github/resource_github_repository_test.go index c4fab6f9d8..e53b0cd93d 100644 --- a/github/resource_github_repository_test.go +++ b/github/resource_github_repository_test.go @@ -1,15 +1,11 @@ package github import ( - "context" - "errors" "fmt" - "log" "regexp" "strings" "testing" - "github.com/google/go-github/v67/github" "github.com/hashicorp/go-cty/cty" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" @@ -20,9 +16,8 @@ import ( ) func TestAccGithubRepositories(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates and updates repositories without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -66,33 +61,20 @@ func TestAccGithubRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("updates a repository's name without error", func(t *testing.T) { + t.Run("updates a repositories name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) oldName := fmt.Sprintf(`tf-acc-test-rename-%[1]s`, randomID) newName := fmt.Sprintf(`%[1]s-renamed`, oldName) @@ -126,41 +108,28 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - // Rename the repo to something else - Config: strings.Replace( - config, - oldName, - newName, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + // Rename the repo to something else + Config: strings.Replace( + config, + oldName, + newName, 1), + Check: checks["after"], + }, + }, }) }) t.Run("imports repositories without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-import-%[1]s" @@ -173,38 +142,25 @@ func TestAccGithubRepositories(t *testing.T) { resource.TestCheckResourceAttrSet("github_repository.test", "name"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_repository.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_repository.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) t.Run("archives repositories without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-archive-%[1]s" @@ -228,39 +184,26 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `archived = false`, - `archived = true`, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `archived = false`, + `archived = true`, 1), + Check: checks["after"], + }, + }, }) }) t.Run("manages the project feature for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-project-%[1]s" @@ -284,39 +227,26 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `has_projects = false`, - `has_projects = true`, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `has_projects = false`, + `has_projects = true`, 1), + Check: checks["after"], + }, + }, }) }) t.Run("manages the default branch feature for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-branch-%[1]s" @@ -346,41 +276,27 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - // Test changing default_branch - { - Config: strings.Replace(config, - `default_branch = "main"`, - `default_branch = "default"`, 1), - Check: checks["after"], - }, - // Test changing default_branch back to main again - { - Config: config, - Check: checks["before"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + // Test changing default_branch + { + Config: strings.Replace(config, + `default_branch = "main"`, + `default_branch = "default"`, 1), + Check: checks["after"], + }, + // Test changing default_branch back to main again + { + Config: config, + Check: checks["before"], + }, + }, }) }) @@ -388,6 +304,7 @@ func TestAccGithubRepositories(t *testing.T) { // Although default_branch is deprecated, for backwards compatibility // we allow setting it to "main". + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-empty-%[1]s" @@ -403,42 +320,29 @@ func TestAccGithubRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - // Test creation with default_branch set - { - Config: config, - Check: check, - }, - // Test that changing another property does not try to set - // default_branch (which would crash). - { - Config: strings.Replace(config, - `acceptance tests`, - `acceptance test`, 1), - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + // Test creation with default_branch set + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + // Test that changing another property does not try to set + // default_branch (which would crash). + { + Config: strings.Replace(config, + `acceptance tests`, + `acceptance test`, 1), + Check: check, + }, + }, }) }) t.Run("manages the license and gitignore feature for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-license-%[1]s" @@ -459,33 +363,20 @@ func TestAccGithubRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("configures topics for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-topic-%[1]s" @@ -501,33 +392,20 @@ func TestAccGithubRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("creates a repository using a template", func(t *testing.T) { + t.Run("creates a repository using a public template", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-template-%s" @@ -539,7 +417,7 @@ func TestAccGithubRepositories(t *testing.T) { } } - `, randomID, testOrganization, "terraform-template-module") + `, randomID, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -548,33 +426,54 @@ func TestAccGithubRepositories(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + }, }) + }) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + t.Run("creates a repository using an org template", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-template-%s" + description = "Terraform acceptance tests %[1]s" + + template { + owner = "%s" + repository = "%s" + } + + } + `, randomID, testAccConf.owner, testAccConf.testOrgTemplateRepository) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "is_template", + "false", + ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) }) t.Run("archives repositories on destroy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-destroy-%[1]s" @@ -599,159 +498,110 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `archived = false`, - `archived = true`, 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + { + Config: strings.Replace(config, + `archived = false`, + `archived = true`, 1), + Check: checks["after"], + }, + }, }) + }) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + t.Run("configures vulnerability alerts for a public repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-pub-vuln-%s", randomID) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + visibility = "public" + } + `, repoName) - t.Run("configures vulnerability alerts", func(t *testing.T) { - t.Run("for a public repository", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-pub-vuln-%s" - visibility = "public" - } - `, randomID) + configUpdate := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + visibility = "public" - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "vulnerability_alerts", - "false", - ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "vulnerability_alerts", - "true", + vulnerability_alerts = true + } + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository.test", "visibility", "public"), + resource.TestCheckResourceAttr("github_repository.test", "vulnerability_alerts", "false"), ), - resource.TestCheckResourceAttr( - "github_repository.test", "visibility", - "public", + }, + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository.test", "visibility", "public"), + resource.TestCheckResourceAttr("github_repository.test", "vulnerability_alerts", "true"), ), - ), - } - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `}`, - "vulnerability_alerts = true\n}", 1), - Check: checks["after"], - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + }, + }, + }) + }) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + t.Run("configures vulnerability alerts for a private repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("tf-acc-test-prv-vuln-%s", randomID) - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + visibility = "private" + } + `, repoName) - t.Run("for a private repository", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-prv-vuln-%s" - visibility = "private" - } - `, randomID) + configUpdate := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + visibility = "private" - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "vulnerability_alerts", - "false", - ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "vulnerability_alerts", - "true", + vulnerability_alerts = true + } + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository.test", "visibility", "private"), + resource.TestCheckResourceAttr("github_repository.test", "vulnerability_alerts", "false"), ), - resource.TestCheckResourceAttr( - "github_repository.test", "visibility", - "private", + }, + { + Config: configUpdate, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository.test", "visibility", "private"), + resource.TestCheckResourceAttr("github_repository.test", "vulnerability_alerts", "true"), ), - ), - } - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `}`, - "vulnerability_alerts = true\n}", 1), - Check: checks["after"], - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) + }, + }, }) }) t.Run("create and modify merge commit strategy without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) mergeCommitTitle := "PR_TITLE" mergeCommitMessage := "BLANK" updatedMergeCommitTitle := "MERGE_MESSAGE" @@ -800,37 +650,24 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) t.Run("create and modify squash merge commit strategy without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) squashMergeCommitTitle := "PR_TITLE" squashMergeCommitMessage := "PR_BODY" updatedSquashMergeCommitTitle := "COMMIT_OR_PR_TITLE" @@ -878,97 +715,66 @@ func TestAccGithubRepositories(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - }) - - t.Run("create a repository with go as primary_language", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - } - resource "github_repository_file" "test" { - repository = github_repository.test.name - file = "test.go" - content = "package main" - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "primary_language", - "Go", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - // Not doing any checks since the file needs to be created before the language can be updated - Config: config, - }, - { - // Re-running the terraform will refresh the language since the go-file has been created - Config: config, - Check: check, - }, + { + Config: configs["after"], + Check: checks["after"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} -func TestAccGithubRepositoryPages(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + // t.Run("create a repository with go as primary_language", func(t *testing.T) { + // randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "tf-acc-%s" + // auto_init = true + // } + // resource "github_repository_file" "test" { + // repository = github_repository.test.name + // file = "test.go" + // content = "package main" + // } + // `, randomID) + + // check := resource.ComposeTestCheckFunc( + // resource.TestCheckResourceAttr("github_repository.test", "primary_language", "Go"), + // ) + + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // ProviderFactories: providerFactories, + // Steps: []resource.TestStep{ + // { + // // Not doing any checks since the file needs to be created before the language can be updated + // Config: config, + // }, + // { + // // Re-running the terraform will refresh the language since the go-file has been created + // Config: config, + // Check: check, + // }, + // }, + // }) + // }) t.Run("manages the legacy pages feature for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-%s" auto_init = true pages { + build_type = "legacy" + source { branch = "main" } @@ -976,214 +782,122 @@ func TestAccGithubRepositoryPages(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "pages.0.source.0.branch", - "main", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository.test", "pages.0.source.0.branch", "main"), + resource.TestCheckResourceAttr("github_repository.test", "pages.0.source.0.path", "/"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("manages the pages from workflow feature for a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - pages { - build_type = "workflow" - } + resource "github_repository" "test" { + name = "tf-acc-%s" + auto_init = true + pages { + build_type = "workflow" } + } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "pages.0.source.0.branch", - "main", - ), - ) - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckNoResourceAttr("github_repository.test", "pages.0.source.#"), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) - t.Run("expand Pages configuration with workflow", func(t *testing.T) { - input := []any{map[string]any{ - "build_type": "workflow", - "source": []any{map[string]any{}}, - }} - - pages := expandPages(input) - if pages == nil { - t.Fatal("pages is nil") + t.Run("manages the security feature for a private repository", func(t *testing.T) { + if !testAccConf.testAdvancedSecurity { + t.Skip("Advanced Security is not enabled for this account") } - if pages.GetBuildType() != "workflow" { - t.Errorf("got %q; want %q", pages.GetBuildType(), "workflow") - } - if pages.GetSource().GetBranch() != "main" { - t.Errorf("got %q; want %q", pages.GetSource().GetBranch(), "main") - } - }) - - t.Run("expand Pages configuration with source", func(t *testing.T) { - input := []any{map[string]any{ - "build_type": "legacy", - "source": []any{map[string]any{ - "branch": "main", - "path": "/docs", - }}, - }} - - pages := expandPages(input) - if pages == nil { - t.Fatal("pages is nil") - } - if pages.GetBuildType() != "legacy" { - t.Errorf("got %q; want %q", pages.GetBuildType(), "legacy") - } - if pages.GetSource().GetBranch() != "main" { - t.Errorf("got %q; want %q", pages.GetSource().GetBranch(), "main") - } - if pages.GetSource().GetPath() != "/docs" { - t.Errorf("got %q; want %q", pages.GetSource().GetPath(), "/docs") - } - }) -} - -func TestAccGithubRepositorySecurity(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("manages the security feature for a repository", func(t *testing.T) { - t.Run("for a private repository", func(t *testing.T) { - t.Skip("organization/individual must have purchased Advanced Security in order to enable it") - config := fmt.Sprintf(` + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-%s" description = "A repository created by Terraform to test security features" visibility = "private" security_and_analysis { advanced_security { - status = "enabled" - } - code_security { - status = "enabled" - } - secret_scanning { + status = "enabled" + } + code_security { + status = "enabled" + } + secret_scanning { status = "enabled" } secret_scanning_push_protection { - status = "enabled" - } - secret_scanning_ai_detection { - status = "enabled" - } - secret_scanning_non_provider_patterns { - status = "enabled" - } + status = "enabled" + } + secret_scanning_ai_detection { + status = "enabled" + } + secret_scanning_non_provider_patterns { + status = "enabled" + } } } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.advanced_security.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.code_security.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning_push_protection.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning_ai_detection.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning_non_provider_patterns.0.status", - "enabled", - ), - ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.advanced_security.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.code_security.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning_push_protection.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning_ai_detection.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning_non_provider_patterns.0.status", + "enabled", + ), + ) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) + }) - t.Run("for a public repository", func(t *testing.T) { - config := fmt.Sprintf(` + t.Run("manages the security feature for a public repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-%s" description = "A repository created by Terraform to test security features" @@ -1200,48 +914,30 @@ func TestAccGithubRepositorySecurity(t *testing.T) { } `, randomID) - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning.0.status", - "enabled", - ), - resource.TestCheckResourceAttr( - "github_repository.test", "security_and_analysis.0.secret_scanning_push_protection.0.status", - "disabled", - ), - ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning.0.status", + "enabled", + ), + resource.TestCheckResourceAttr( + "github_repository.test", "security_and_analysis.0.secret_scanning_push_protection.0.status", + "disabled", + ), + ) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) }) -} - -func TestAccGithubRepositoryVisibility(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("creates repos with private visibility", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "private" { name = "tf-acc-test-visibility-private-%s" @@ -1256,35 +952,20 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("creates repos with internal visibility", func(t *testing.T) { - t.Skip("organization used in automated tests does not support internal repositories") - + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "internal" { name = "tf-acc-test-visibility-internal-%s" @@ -1299,33 +980,20 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("updates repos to private visibility", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "public" { name = "tf-acc-test-visibility-public-%s" @@ -1349,37 +1017,24 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: reconfigureVisibility(config, "private"), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: reconfigureVisibility(config, "private"), + Check: checks["after"], + }, + }, }) }) t.Run("updates repos to public visibility", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-prv-vuln-%s" @@ -1406,39 +1061,26 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `}`, - "vulnerability_alerts = true\n}", 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `}`, + "vulnerability_alerts = true\n}", 1), + Check: checks["after"], + }, + }, }) }) t.Run("updates repos to internal visibility", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "tf-acc-test-prv-vuln-%s" @@ -1465,39 +1107,26 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: strings.Replace(config, - `}`, - "vulnerability_alerts = true\n}", 1), - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `}`, + "vulnerability_alerts = true\n}", 1), + Check: checks["after"], + }, + }, }) }) t.Run("sets private visibility for repositories created by a template", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "private" { name = "tf-acc-test-visibility-private-%s" @@ -1507,7 +1136,7 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { repository = "%s" } } - `, randomID, testOrganization, "terraform-template-module") + `, randomID, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1520,134 +1149,60 @@ func TestAccGithubRepositoryVisibility(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } -func TestAccGithubRepositoryWebCommitSignoffRequired(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - - t.Run("changes the web_commit_signoff_required attribute for a repository", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - web_commit_signoff_required = true - } - `, randomID) - - check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "web_commit_signoff_required", - "true", - ), - ) +func Test_expandPages(t *testing.T) { + t.Run("expand Pages configuration with workflow", func(t *testing.T) { + input := []any{map[string]any{ + "build_type": "workflow", + "source": []any{map[string]any{}}, + }} - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - }, - }) + pages := expandPages(input) + if pages == nil { + t.Fatal("pages is nil") + } + if pages.GetBuildType() != "workflow" { + t.Errorf("got %q; want %q", pages.GetBuildType(), "workflow") + } + if pages.GetSource().GetBranch() != "main" { + t.Errorf("got %q; want %q", pages.GetSource().GetBranch(), "main") } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) }) - // Test that setting any other setting than web_commit_signoff_required - // being set, doesn't set the value of web_commit_signoff_required to true - // or false in the GitHub API call. - t.Run("changes a non web_commit_signoff_required attribute for a repository", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - allow_merge_commit = true - web_commit_signoff_required = true - } - `, randomID) + t.Run("expand Pages configuration with source", func(t *testing.T) { + input := []any{map[string]any{ + "build_type": "legacy", + "source": []any{map[string]any{ + "branch": "main", + "path": "/docs", + }}, + }} - checks := map[string]resource.TestCheckFunc{ - "before": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "web_commit_signoff_required", - "true", - ), - ), - "after": resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "web_commit_signoff_required", - "true", - ), - ), + pages := expandPages(input) + if pages == nil { + t.Fatal("pages is nil") } - - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["before"], - }, - { - Config: config, - Check: checks["after"], - }, - }, - }) + if pages.GetBuildType() != "legacy" { + t.Errorf("got %q; want %q", pages.GetBuildType(), "legacy") + } + if pages.GetSource().GetBranch() != "main" { + t.Errorf("got %q; want %q", pages.GetSource().GetBranch(), "main") + } + if pages.GetSource().GetPath() != "/docs" { + t.Errorf("got %q; want %q", pages.GetSource().GetPath(), "/docs") } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) }) } @@ -1675,39 +1230,6 @@ func TestGithubRepositoryTopicFailsValidationWhenOverMaxCharacters(t *testing.T) } } -func testSweepRepositories(region string) error { - meta, err := sharedConfigForRegion() - if err != nil { - return err - } - - client := meta.(*Owner).v3client - - repos, _, err := client.Repositories.ListByUser(context.TODO(), meta.(*Owner).name, nil) - if err != nil { - return err - } - - for _, r := range repos { - if name := r.GetName(); strings.HasPrefix(name, "tf-acc-") || strings.HasPrefix(name, "foo-") { - log.Printf("[DEBUG] Destroying Repository %s", name) - - if _, err := client.Repositories.Delete(context.TODO(), meta.(*Owner).name, name); err != nil { - return err - } - } - } - - return nil -} - -func init() { - resource.AddTestSweepers("github_repository", &resource.Sweeper{ - Name: "github_repository", - F: testSweepRepositories, - }) -} - func reconfigureVisibility(config, visibility string) string { re := regexp.MustCompile(`visibility = "(.*)"`) newConfig := re.ReplaceAllString( @@ -1818,29 +1340,15 @@ func TestAccGithubRepository_fork(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + }, }) }) @@ -1900,152 +1408,123 @@ func TestAccGithubRepository_fork(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: initialConfig, - Check: checks["before"], - }, - { - Config: updatedConfig, - Check: checks["after"], - }, - { - ResourceName: "github_repository.forked_update", - ImportState: true, - ImportStateVerify: true, - ImportStateVerifyIgnore: []string{"auto_init"}, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: initialConfig, + Check: checks["before"], }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - }) - - t.Run("can migrate a forked repository from a previous framework version", func(t *testing.T) { - rName := fmt.Sprintf("terraform-provider-github-%s", randomID) - olderConfig := fmt.Sprintf(` - import { - to = github_repository.forked - id = "%[1]s" - } - resource "github_repository" "forked" { - name = "%[1]s" - description = "Terraform acceptance test - forked repository %[1]s" - } - `, rName) - newerConfig := fmt.Sprintf(` - resource "github_repository" "forked" { - name = "%[1]s" - description = "Terraform acceptance test - forked repository %[1]s" - fork = true - source_owner = "integrations" - source_repo = "terraform-provider-github" - } - `, rName) - - testCase := func(t *testing.T, mode string) { - providers := []*schema.Provider{testAccProvider} - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Steps: []resource.TestStep{ - { - ExternalProviders: map[string]resource.ExternalProvider{ - "github": { - VersionConstraint: "~> 6.7.0", - Source: "integrations/github", - }, - }, - PreConfig: func() { - err := createForkedRepository(rName) - if err != nil { - t.Fatalf("failed to create fork of %s: %v", rName, err) - } - }, - Config: olderConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckNoResourceAttr( - "github_repository.forked", "fork", - ), - resource.TestCheckNoResourceAttr( - "github_repository.forked", "source_owner", - ), - resource.TestCheckNoResourceAttr( - "github_repository.forked", "source_repo", - ), - ), - }, - { - ProviderFactories: testAccProviderFactories(&providers), - Config: newerConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.forked", "fork", - "true", - ), - resource.TestCheckResourceAttr( - "github_repository.forked", "source_owner", - "integrations", - ), - resource.TestCheckResourceAttr( - "github_repository.forked", "source_repo", - "terraform-provider-github", - ), - ), - }, + { + Config: updatedConfig, + Check: checks["after"], }, - }) - } - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) - }) - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") + { + ResourceName: "github_repository.forked_update", + ImportState: true, + ImportStateVerify: true, + ImportStateVerifyIgnore: []string{"auto_init"}, + }, + }, }) }) -} - -func createForkedRepository(repositoryName string) error { - config := Config{BaseURL: "https://api.github.com/", Owner: testOrganizationFunc(), Token: testToken} - meta, err := config.Meta() - if err != nil { - return fmt.Errorf("failed to create client: %w", err) - } - client := meta.(*Owner).v3client - orgName := meta.(*Owner).name - ctx := context.TODO() - - _, _, err = client.Repositories.CreateFork(ctx, "integrations", "snappydoo", &github.RepositoryCreateForkOptions{ - Organization: orgName, - Name: repositoryName, - }) - acceptedError := &github.AcceptedError{} - if err != nil { - if errors.As(err, &acceptedError) { - return nil - } - return fmt.Errorf("failed to create fork: %w", err) - } - return nil + // t.Run("can migrate a forked repository from a previous framework version", func(t *testing.T) { + // rName := fmt.Sprintf("terraform-provider-github-%s", randomID) + // olderConfig := fmt.Sprintf(` + // import { + // to = github_repository.forked + // id = "%[1]s" + // } + // resource "github_repository" "forked" { + // name = "%[1]s" + // description = "Terraform acceptance test - forked repository %[1]s" + // } + // `, rName) + // newerConfig := fmt.Sprintf(` + // resource "github_repository" "forked" { + // name = "%[1]s" + // description = "Terraform acceptance test - forked repository %[1]s" + // fork = true + // source_owner = "integrations" + // source_repo = "terraform-provider-github" + // } + // `, rName) + + // providers := []*schema.Provider{testAccProvider} + // resource.Test(t, resource.TestCase{ + // PreCheck: func() { skipUnauthenticated(t) }, + // Steps: []resource.TestStep{ + // { + // ExternalProviders: map[string]resource.ExternalProvider{ + // "github": { + // VersionConstraint: "~> 6.7.0", + // Source: "integrations/github", + // }, + // }, + // PreConfig: func() { + // err := createForkedRepository(rName) + // if err != nil { + // t.Fatalf("failed to create fork of %s: %v", rName, err) + // } + // }, + // Config: olderConfig, + // Check: resource.ComposeTestCheckFunc( + // resource.TestCheckNoResourceAttr( + // "github_repository.forked", "fork", + // ), + // resource.TestCheckNoResourceAttr( + // "github_repository.forked", "source_owner", + // ), + // resource.TestCheckNoResourceAttr( + // "github_repository.forked", "source_repo", + // ), + // ), + // }, + // { + // ProviderFactories: testAccProviderFactories(&providers), + // Config: newerConfig, + // Check: resource.ComposeTestCheckFunc( + // resource.TestCheckResourceAttr( + // "github_repository.forked", "fork", + // "true", + // ), + // resource.TestCheckResourceAttr( + // "github_repository.forked", "source_owner", + // "integrations", + // ), + // resource.TestCheckResourceAttr( + // "github_repository.forked", "source_repo", + // "terraform-provider-github", + // ), + // ), + // }, + // }, + // }) + // }) } + +// func createForkedRepository(ctx context.Context, repositoryName string) error { +// config := Config{BaseURL: "https://api.github.com/", Owner: testAccConf.owner, Token: testAccConf.token} +// meta, err := config.Meta() +// if err != nil { +// return fmt.Errorf("failed to create client: %w", err) +// } +// client := meta.(*Owner).v3client +// orgName := meta.(*Owner).name + +// _, _, err = client.Repositories.CreateFork(ctx, "integrations", "snappydoo", &github.RepositoryCreateForkOptions{ +// Organization: orgName, +// Name: repositoryName, +// }) + +// acceptedError := &github.AcceptedError{} +// if err != nil { +// if errors.As(err, &acceptedError) { +// return nil +// } +// return fmt.Errorf("failed to create fork: %w", err) +// } +// return nil +// } diff --git a/github/resource_github_repository_topics_test.go b/github/resource_github_repository_topics_test.go index d5f571e202..1548a49a35 100644 --- a/github/resource_github_repository_topics_test.go +++ b/github/resource_github_repository_topics_test.go @@ -30,34 +30,20 @@ func TestAccGithubRepositoryTopics(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "topics.#", "2"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: resourceName, + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) @@ -97,33 +83,19 @@ func TestAccGithubRepositoryTopics(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "topics.#", "3"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configBefore, - Check: checkBefore, - }, - { - Config: configAfter, - Check: checkAfter, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configBefore, + Check: checkBefore, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configAfter, + Check: checkAfter, + }, + }, }) }) } diff --git a/github/resource_github_repository_webhook_test.go b/github/resource_github_repository_webhook_test.go index 8594b447b3..8105f2e259 100644 --- a/github/resource_github_repository_webhook_test.go +++ b/github/resource_github_repository_webhook_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubRepositoryWebhook(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates repository webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "test-%[1]s" @@ -19,7 +18,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] + depends_on = [github_repository.test] repository = "test-%[1]s" configuration { @@ -41,33 +40,20 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports repository webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_repository" "test" { name = "test-%[1]s" @@ -75,7 +61,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] + depends_on = [github_repository.test] repository = "test-%[1]s" configuration { url = "https://google.de/webhook" @@ -88,39 +74,26 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { check := resource.ComposeTestCheckFunc() - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_repository_webhook.test", - ImportState: true, - ImportStateVerify: true, - ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_repository_webhook.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("test-%s/", randomID), + }, + }, }) }) t.Run("updates repository webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) configs := map[string]string{ "before": fmt.Sprintf(` resource "github_repository" "test" { @@ -129,7 +102,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] + depends_on = [github_repository.test] repository = "test-%[1]s" configuration { @@ -148,7 +121,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] + depends_on = [github_repository.test] repository = "test-%[1]s" configuration { @@ -172,33 +145,19 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: configs["before"], - Check: checks["before"], - }, - { - Config: configs["after"], - Check: checks["after"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: configs["before"], + Check: checks["before"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configs["after"], + Check: checks["after"], + }, + }, }) }) } diff --git a/github/resource_github_team_members_test.go b/github/resource_github_team_members_test.go index 95aa763a57..cbf964b6bb 100644 --- a/github/resource_github_team_members_test.go +++ b/github/resource_github_team_members_test.go @@ -3,72 +3,87 @@ package github import ( "context" "fmt" - "strconv" "testing" - "github.com/google/go-github/v67/github" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) func TestAccGithubTeamMembers(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") + if len(testAccConf.testOrgUser) == 0 { + t.Skip("No test user provided") } - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - resourceName := "github_team_members.test_team_members" + t.Run("creates a team & members configured with defaults", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("tf-acc-test-team-%s", randomID) - var membership github.Membership + config := fmt.Sprintf(` +resource "github_team" "test" { + name = "%s" +} - t.Run("creates a team & members configured with defaults", func(t *testing.T) { - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamMembersDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamMembersConfig(randomID, testCollaborator, "member"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembersExists(resourceName, &membership), - testAccCheckGithubTeamMembersRoleState(resourceName, "member", &membership), - ), - }, - { - Config: testAccGithubTeamMembersConfig(randomID, testCollaborator, "maintainer"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembersExists(resourceName, &membership), - testAccCheckGithubTeamMembersRoleState(resourceName, "maintainer", &membership), - ), - }, - { - ResourceName: resourceName, - ImportState: true, - ImportStateVerify: true, - }, - }, - }) - } +resource "github_team_members" "test" { + team_id = github_team.test.id - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) + members { + username = "%s" + role = "member" + } +} +`, teamName, testAccConf.testOrgUser) - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) + configUpdated := fmt.Sprintf(` +resource "github_team" "test" { + name = "%s" +} + +resource "github_team_members" "test" { + team_id = github_team.test.id - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + members { + username = "%s" + role = "maintainer" + } +} +`, teamName, testAccConf.testOrgUser) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamMembersDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_team_members.test", "members.#"), + resource.TestCheckResourceAttr("github_team_members.test", "members.#", "1"), + resource.TestCheckResourceAttr("github_team_members.test", "members.0.username", testAccConf.testOrgUser), + resource.TestCheckResourceAttr("github_team_members.test", "members.0.role", "member"), + ), + }, + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet("github_team_members.test", "members.#"), + resource.TestCheckResourceAttr("github_team_members.test", "members.#", "1"), + resource.TestCheckResourceAttr("github_team_members.test", "members.0.username", testAccConf.testOrgUser), + resource.TestCheckResourceAttr("github_team_members.test", "members.0.role", "member"), + ), + }, + }, }) }) } func testAccCheckGithubTeamMembersDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgId := meta.id for _, rs := range s.RootModule().Resources { if rs.Type != "github_team_members" { @@ -77,12 +92,12 @@ func testAccCheckGithubTeamMembersDestroy(s *terraform.State) error { teamIdString := rs.Primary.ID - teamId, err := strconv.ParseInt(teamIdString, 10, 64) + teamId, err := getTeamID(teamIdString, meta) if err != nil { return unconvertibleIdErr(teamIdString, err) } - members, resp, err := conn.Teams.ListTeamMembersByID(context.TODO(), + members, resp, err := conn.Teams.ListTeamMembersByID(context.Background(), orgId, teamId, nil) if err == nil { if len(members) > 0 { @@ -96,114 +111,3 @@ func testAccCheckGithubTeamMembersDestroy(s *terraform.State) error { } return nil } - -func testAccCheckGithubTeamMembersExists(n string, membership *github.Membership) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("no team ID is set") - } - - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id - teamIdString := rs.Primary.ID - - teamId, err := strconv.ParseInt(teamIdString, 10, 64) - if err != nil { - return unconvertibleIdErr(teamIdString, err) - } - - members, _, err := conn.Teams.ListTeamMembersByID(context.TODO(), orgId, teamId, nil) - if err != nil { - return err - } - - if len(members) != 1 { - return fmt.Errorf("team has not one member: %d", len(members)) - } - - TeamMembership, _, err := conn.Teams.GetTeamMembershipByID(context.TODO(), orgId, teamId, *members[0].Login) - if err != nil { - return err - } - *membership = *TeamMembership - return nil - } -} - -func testAccCheckGithubTeamMembersRoleState(n, expected string, membership *github.Membership) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[n] - if !ok { - return fmt.Errorf("not found: %s", n) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("no team ID is set") - } - - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id - teamIdString := rs.Primary.ID - - teamId, err := strconv.ParseInt(teamIdString, 10, 64) - if err != nil { - return unconvertibleIdErr(teamIdString, err) - } - - members, _, err := conn.Teams.ListTeamMembersByID(context.TODO(), orgId, teamId, nil) - if err != nil { - return err - } - - if len(members) != 1 { - return fmt.Errorf("team has not one member: %d", len(members)) - } - - TeamMembers, _, err := conn.Teams.GetTeamMembershipByID(context.TODO(), - orgId, teamId, *members[0].Login) - if err != nil { - return err - } - - resourceRole := membership.GetRole() - actualRole := TeamMembers.GetRole() - - if resourceRole != expected { - return fmt.Errorf("team membership role %v in resource does match expected state of %v", resourceRole, expected) - } - - if resourceRole != actualRole { - return fmt.Errorf("team membership role %v in resource does match actual state of %v", resourceRole, actualRole) - } - return nil - } -} - -func testAccGithubTeamMembersConfig(randString, username, role string) string { - return fmt.Sprintf(` -resource "github_membership" "test_org_membership" { - username = "%s" - role = "member" -} - -resource "github_team" "test_team" { - name = "tf-acc-test-team-membership-%s" - description = "Terraform acc test group" -} - -resource "github_team_members" "test_team_members" { - team_id = "${github_team.test_team.id}" - members { - username = "%s" - role = "%s" - } - - depends_on = [github_membership.test_org_membership] -} -`, username, randString, username, role) -} diff --git a/github/resource_github_team_membership_test.go b/github/resource_github_team_membership_test.go index 8e11c657c2..e79a5d70cf 100644 --- a/github/resource_github_team_membership_test.go +++ b/github/resource_github_team_membership_test.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "strconv" "testing" "github.com/google/go-github/v67/github" @@ -13,107 +12,85 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccGithubTeamMembership_basic(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") - } - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) +func TestAccGithubTeamMembership(t *testing.T) { + if len(testAccConf.testOrgUser) == 0 { + t.Skip("No test user provided") } - var membership github.Membership - - rn := "github_team_membership.test_team_membership" - rns := "github_team_membership.test_team_membership_slug" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamMembershipDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamMembershipConfig(randString, testCollaborator, "member"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembershipExists(rn, &membership), - testAccCheckGithubTeamMembershipRoleState(rn, "member", &membership), - testAccCheckGithubTeamMembershipExists(rns, &membership), - testAccCheckGithubTeamMembershipRoleState(rns, "member", &membership), - ), - }, - { - Config: testAccGithubTeamMembershipConfig(randString, testCollaborator, "maintainer"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembershipExists(rn, &membership), - testAccCheckGithubTeamMembershipRoleState(rn, "maintainer", &membership), - testAccCheckGithubTeamMembershipExists(rns, &membership), - testAccCheckGithubTeamMembershipRoleState(rns, "maintainer", &membership), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, - }, - { - ResourceName: rns, - ImportState: true, - ImportStateVerify: true, + t.Run("creates a team membership", func(t *testing.T) { + ctx := t.Context() + + var membership github.Membership + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamMembershipDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamMembershipConfig(randString, testAccConf.testOrgUser, "member"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubTeamMembershipExists(ctx, "github_team_membership.test_team_membership", &membership), + testAccCheckGithubTeamMembershipRoleState(ctx, "github_team_membership.test_team_membership", "member", &membership), + testAccCheckGithubTeamMembershipExists(ctx, "github_team_membership.test_team_membership_slug", &membership), + testAccCheckGithubTeamMembershipRoleState(ctx, "github_team_membership.test_team_membership_slug", "member", &membership), + ), + }, + { + Config: testAccGithubTeamMembershipConfig(randString, testAccConf.testOrgUser, "maintainer"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubTeamMembershipExists(ctx, "github_team_membership.test_team_membership", &membership), + testAccCheckGithubTeamMembershipRoleState(ctx, "github_team_membership.test_team_membership", "maintainer", &membership), + testAccCheckGithubTeamMembershipExists(ctx, "github_team_membership.test_team_membership_slug", &membership), + testAccCheckGithubTeamMembershipRoleState(ctx, "github_team_membership.test_team_membership_slug", "maintainer", &membership), + ), + }, }, - }, + }) }) -} - -func TestAccGithubTeamMembership_caseInsensitive(t *testing.T) { - if testCollaborator == "" { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` is not set") - } - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } - - var membership github.Membership - var otherMembership github.Membership - - rn := "github_team_membership.test_team_membership" - randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) - - otherCase := flipUsernameCase(testCollaborator) - - if testCollaborator == otherCase { - t.Skip("Skipping because `GITHUB_TEST_COLLABORATOR` has no letters to flip case") - } - resource.Test(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamMembershipDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamMembershipConfig(randString, testCollaborator, "member"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembershipExists(rn, &membership), - ), + t.Run("is case insensitive", func(t *testing.T) { + ctx := t.Context() + + var membership github.Membership + var otherMembership github.Membership + + rn := "github_team_membership.test_team_membership" + randString := acctest.RandStringFromCharSet(10, acctest.CharSetAlphaNum) + + otherCase := flipUsernameCase(testAccConf.testOrgUser) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamMembershipDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamMembershipConfig(randString, testAccConf.testOrgUser, "member"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubTeamMembershipExists(ctx, rn, &membership), + ), + }, + { + Config: testAccGithubTeamMembershipConfig(randString, otherCase, "member"), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubTeamMembershipExists(ctx, rn, &otherMembership), + testAccGithubTeamMembershipTheSame(&membership, &otherMembership), + ), + }, }, - { - Config: testAccGithubTeamMembershipConfig(randString, otherCase, "member"), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamMembershipExists(rn, &otherMembership), - testAccGithubTeamMembershipTheSame(&membership, &otherMembership), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, - }, - }, + }) }) } func testAccCheckGithubTeamMembershipDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgId := meta.id for _, rs := range s.RootModule().Resources { if rs.Type != "github_team_membership" { @@ -125,12 +102,12 @@ func testAccCheckGithubTeamMembershipDestroy(s *terraform.State) error { return err } - teamId, err := strconv.ParseInt(teamIdString, 10, 64) + teamId, err := getTeamID(teamIdString, meta) if err != nil { return unconvertibleIdErr(teamIdString, err) } - membership, resp, err := conn.Teams.GetTeamMembershipByID(context.TODO(), + membership, resp, err := conn.Teams.GetTeamMembershipByID(context.Background(), orgId, teamId, username) if err == nil { if membership != nil { @@ -145,7 +122,7 @@ func testAccCheckGithubTeamMembershipDestroy(s *terraform.State) error { return nil } -func testAccCheckGithubTeamMembershipExists(n string, membership *github.Membership) resource.TestCheckFunc { +func testAccCheckGithubTeamMembershipExists(ctx context.Context, n string, membership *github.Membership) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -156,19 +133,23 @@ func testAccCheckGithubTeamMembershipExists(n string, membership *github.Members return fmt.Errorf("no team membership ID is set") } - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgId := meta.id teamIdString, username, err := parseTwoPartID(rs.Primary.ID, "team_id", "username") if err != nil { return err } - teamId, err := strconv.ParseInt(teamIdString, 10, 64) + teamId, err := getTeamID(teamIdString, meta) if err != nil { return unconvertibleIdErr(teamIdString, err) } - teamMembership, _, err := conn.Teams.GetTeamMembershipByID(context.TODO(), orgId, teamId, username) + teamMembership, _, err := conn.Teams.GetTeamMembershipByID(ctx, orgId, teamId, username) if err != nil { return err } @@ -177,7 +158,7 @@ func testAccCheckGithubTeamMembershipExists(n string, membership *github.Members } } -func testAccCheckGithubTeamMembershipRoleState(n, expected string, membership *github.Membership) resource.TestCheckFunc { +func testAccCheckGithubTeamMembershipRoleState(ctx context.Context, n, expected string, membership *github.Membership) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[n] if !ok { @@ -188,19 +169,22 @@ func testAccCheckGithubTeamMembershipRoleState(n, expected string, membership *g return fmt.Errorf("no team membership ID is set") } - conn := testAccProvider.Meta().(*Owner).v3client - orgId := testAccProvider.Meta().(*Owner).id + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgId := meta.id teamIdString, username, err := parseTwoPartID(rs.Primary.ID, "team_id", "username") if err != nil { return err } - teamId, err := strconv.ParseInt(teamIdString, 10, 64) + teamId, err := getTeamID(teamIdString, meta) if err != nil { return unconvertibleIdErr(teamIdString, err) } - teamMembership, _, err := conn.Teams.GetTeamMembershipByID(context.TODO(), - orgId, teamId, username) + teamMembership, _, err := conn.Teams.GetTeamMembershipByID(ctx, orgId, teamId, username) if err != nil { return err } @@ -221,11 +205,6 @@ func testAccCheckGithubTeamMembershipRoleState(n, expected string, membership *g func testAccGithubTeamMembershipConfig(randString, username, role string) string { return fmt.Sprintf(` -resource "github_membership" "test_org_membership" { - username = "%s" - role = "member" -} - resource "github_team" "test_team" { name = "tf-acc-test-team-membership-%s" description = "Terraform acc test group" @@ -237,17 +216,17 @@ resource "github_team" "test_team_slug" { } resource "github_team_membership" "test_team_membership" { - team_id = "${github_team.test_team.id}" + team_id = github_team.test_team.id username = "%s" role = "%s" } resource "github_team_membership" "test_team_membership_slug" { - team_id = "${github_team.test_team_slug.slug}" + team_id = github_team.test_team_slug.slug username = "%s" role = "%s" } -`, username, randString, randString, username, role, username, role) +`, randString, randString, username, role, username, role) } func testAccGithubTeamMembershipTheSame(orig, other *github.Membership) resource.TestCheckFunc { diff --git a/github/resource_github_team_repository_test.go b/github/resource_github_team_repository_test.go index fd9252bbff..f7e3045200 100644 --- a/github/resource_github_team_repository_test.go +++ b/github/resource_github_team_repository_test.go @@ -10,9 +10,8 @@ import ( ) func TestAccGithubTeamRepository(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("manages team permissions to a repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-repo-%s" @@ -63,57 +62,44 @@ func TestAccGithubTeamRepository(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["pull"], - }, - { - Config: strings.Replace(config, - `permission = "pull"`, - `permission = "triage"`, 1), - Check: checks["triage"], - }, - { - Config: strings.Replace(config, - `permission = "pull"`, - `permission = "push"`, 1), - Check: checks["push"], - }, - { - Config: strings.Replace(config, - `permission = "pull"`, - `permission = "maintain"`, 1), - Check: checks["maintain"], - }, - { - Config: strings.Replace(config, - `permission = "pull"`, - `permission = "admin"`, 1), - Check: checks["admin"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["pull"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `permission = "pull"`, + `permission = "triage"`, 1), + Check: checks["triage"], + }, + { + Config: strings.Replace(config, + `permission = "pull"`, + `permission = "push"`, 1), + Check: checks["push"], + }, + { + Config: strings.Replace(config, + `permission = "pull"`, + `permission = "maintain"`, 1), + Check: checks["maintain"], + }, + { + Config: strings.Replace(config, + `permission = "pull"`, + `permission = "admin"`, 1), + Check: checks["admin"], + }, + }, }) }) t.Run("accepts both team slug and team ID for `team_id`", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-repo-%s" @@ -135,35 +121,21 @@ func TestAccGithubTeamRepository(t *testing.T) { resource.TestCheckResourceAttrSet("github_team_repository.test", "team_id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - Config: strings.Replace(config, - `github_team.test.id`, - `github_team.test.slug`, 1), - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `github_team.test.id`, + `github_team.test.slug`, 1), + Check: check, + }, + }, }) }) } @@ -209,31 +181,30 @@ func TestAccGithubTeamRepositoryArchivedRepo(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_team_repository.test", "permission", - "pull", - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_team_repository.test", "permission", + "pull", ), - }, - { - Config: archivedConfig, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr( - "github_repository.test", "archived", - "true", - ), + ), + }, + { + Config: archivedConfig, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository.test", "archived", + "true", ), - }, - { - Config: fmt.Sprintf(` + ), + }, + { + Config: fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-archive-%s" description = "test team for archived repo" @@ -245,13 +216,8 @@ func TestAccGithubTeamRepositoryArchivedRepo(t *testing.T) { archived = true } `, randomID), - }, }, - }) - } - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_team_settings_test.go b/github/resource_github_team_settings_test.go index 5607e7bb09..cb9544c481 100644 --- a/github/resource_github_team_settings_test.go +++ b/github/resource_github_team_settings_test.go @@ -10,10 +10,9 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" ) -func TestCanUseIDOrSlugForTeamIDWhenChangingSettings(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - +func TestAccGithubTeamSettings(t *testing.T) { t.Run("manages team settings can use team_id id and slug", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-repo-%s" @@ -29,43 +28,26 @@ func TestCanUseIDOrSlugForTeamIDWhenChangingSettings(t *testing.T) { resource.TestCheckResourceAttrSet("github_team_settings.test", "team_id"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - Config: strings.Replace(config, - `github_team.test.id`, - `github_team.test.slug`, 1), - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `github_team.test.id`, + `github_team.test.slug`, 1), + Check: check, + }, + }, }) }) -} - -func TestCanUpdateTeamSettings(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("manages team code review settings", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-repo-%s" @@ -109,55 +91,38 @@ func TestCanUpdateTeamSettings(t *testing.T) { ), } - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: checks["round_robin"], - }, - { - Config: strings.Replace(config, - `algorithm = "ROUND_ROBIN"`, - `algorithm = "LOAD_BALANCE"`, 1), - Check: checks["load_balance"], - }, - { - Config: strings.Replace(config, - `member_count = 1`, - `member_count = 3`, 1), - Check: checks["review_count"], - }, - { - Config: strings.Replace(config, - `notify = true`, - `notify = false`, 1), - Check: checks["notify"], - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: checks["round_robin"], }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: strings.Replace(config, + `algorithm = "ROUND_ROBIN"`, + `algorithm = "LOAD_BALANCE"`, 1), + Check: checks["load_balance"], + }, + { + Config: strings.Replace(config, + `member_count = 1`, + `member_count = 3`, 1), + Check: checks["review_count"], + }, + { + Config: strings.Replace(config, + `notify = true`, + `notify = false`, 1), + Check: checks["notify"], + }, + }, }) }) -} - -func TestCannotUseReviewSettingsIfDisabled(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("cannot manage team code review settings if disabled", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-test-team-repo-%s" @@ -174,31 +139,17 @@ func TestCannotUseReviewSettingsIfDisabled(t *testing.T) { } `, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: strings.Replace(config, - `algorithm = "ROUND_ROBIN"`, - `algorithm = "invalid"`, 1), - ExpectError: regexp.MustCompile(`review request delegation algorithm must be one of \[.*\]`), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: strings.Replace(config, + `algorithm = "ROUND_ROBIN"`, + `algorithm = "invalid"`, 1), + ExpectError: regexp.MustCompile(`review request delegation algorithm must be one of \[.*\]`), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_team_sync_group_mapping_test.go b/github/resource_github_team_sync_group_mapping_test.go index 7ec58a5eed..34aa18ab6d 100644 --- a/github/resource_github_team_sync_group_mapping_test.go +++ b/github/resource_github_team_sync_group_mapping_test.go @@ -13,141 +13,135 @@ import ( ) func TestAccGithubTeamSyncGroupMapping_basic(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - teamName := acctest.RandomWithPrefix("tf-acc-test-%s") - rn := "github_team_sync_group_mapping.test_mapping" + t.Run("creates a team sync group mapping", func(t *testing.T) { + teamName := acctest.RandomWithPrefix("tf-acc-test-%s") + rn := "github_team_sync_group_mapping.test_mapping" - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamSyncGroupMappingConfig(teamName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "group.#", "3"), - resource.TestCheckResourceAttrSet(rn, "group.3924494127.group_id"), - resource.TestCheckResourceAttrSet(rn, "group.3924494127.group_name"), - resource.TestCheckResourceAttrSet(rn, "group.4283356133.group_id"), - resource.TestCheckResourceAttrSet(rn, "group.4283356133.group_name"), - resource.TestCheckResourceAttrSet(rn, "group.451718421.group_id"), - resource.TestCheckResourceAttrSet(rn, "group.451718421.group_name"), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), - ImportStateVerify: true, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamSyncGroupMappingConfig(teamName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "group.#", "3"), + resource.TestCheckResourceAttrSet(rn, "group.3924494127.group_id"), + resource.TestCheckResourceAttrSet(rn, "group.3924494127.group_name"), + resource.TestCheckResourceAttrSet(rn, "group.4283356133.group_id"), + resource.TestCheckResourceAttrSet(rn, "group.4283356133.group_name"), + resource.TestCheckResourceAttrSet(rn, "group.451718421.group_id"), + resource.TestCheckResourceAttrSet(rn, "group.451718421.group_name"), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), + ImportStateVerify: true, + }, }, - }, + }) }) -} -func TestAccGithubTeamSyncGroupMapping_disappears(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - teamName := acctest.RandomWithPrefix("tf-acc-test-%s") - rn := "github_team_sync_group_mapping.test_mapping" + t.Run("creates a team sync group mapping and then deletes it", func(t *testing.T) { + teamName := acctest.RandomWithPrefix("tf-acc-test-%s") + rn := "github_team_sync_group_mapping.test_mapping" - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamSyncGroupMappingConfig(teamName), - Check: resource.ComposeTestCheckFunc( - testAccCheckGithubTeamSyncGroupMappingDisappears(rn), - ), - ExpectNonEmptyPlan: true, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamSyncGroupMappingConfig(teamName), + Check: resource.ComposeTestCheckFunc( + testAccCheckGithubTeamSyncGroupMappingDisappears(t.Context(), rn), + ), + ExpectNonEmptyPlan: true, + }, }, - }, + }) }) -} -func TestAccGithubTeamSyncGroupMapping_update(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - teamName := acctest.RandomWithPrefix("tf-acc-test-%s") - description := "tf-acc-group-description-update" - rn := "github_team_sync_group_mapping.test_mapping" + t.Run("creates a team sync group mapping and then updates it", func(t *testing.T) { + teamName := acctest.RandomWithPrefix("tf-acc-test-%s") + description := "tf-acc-group-description-update" + rn := "github_team_sync_group_mapping.test_mapping" - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamSyncGroupMappingConfig(teamName), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), - ImportStateVerify: true, - }, - { - Config: testAccGithubTeamSyncGroupMappingEmptyConfig(teamName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "group.#", "0"), - ), - }, - { - Config: testAccGithubTeamSyncGroupMappingConfig(teamName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "group.#", "3"), - ), + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamSyncGroupMappingConfig(teamName), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), + ImportStateVerify: true, + }, + { + Config: testAccGithubTeamSyncGroupMappingEmptyConfig(teamName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "group.#", "0"), + ), + }, + { + Config: testAccGithubTeamSyncGroupMappingConfig(teamName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "group.#", "3"), + ), + }, + { + Config: testAccGithubTeamSyncGroupMappingAddGroupAndUpdateConfig(teamName, description), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "group.#", "3"), + resource.TestCheckResourceAttr(rn, "group.1385744695.group_description", description), + resource.TestCheckResourceAttr(rn, "group.2749525965.group_description", description), + resource.TestCheckResourceAttr(rn, "group.3830341445.group_description", description), + ), + }, }, - { - Config: testAccGithubTeamSyncGroupMappingAddGroupAndUpdateConfig(teamName, description), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "group.#", "3"), - resource.TestCheckResourceAttr(rn, "group.1385744695.group_description", description), - resource.TestCheckResourceAttr(rn, "group.2749525965.group_description", description), - resource.TestCheckResourceAttr(rn, "group.3830341445.group_description", description), - ), - }, - }, + }) }) -} -func TestAccGithubTeamSyncGroupMapping_empty(t *testing.T) { - if isEnterprise != "true" { - t.Skip("Skipping because `ENTERPRISE_ACCOUNT` is not set or set to false") - } - teamName := acctest.RandomWithPrefix("tf-acc-test-%s") - rn := "github_team_sync_group_mapping.test_mapping" + t.Run("creates empty team sync group mapping", func(t *testing.T) { + teamName := acctest.RandomWithPrefix("tf-acc-test-%s") + rn := "github_team_sync_group_mapping.test_mapping" - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubTeamSyncGroupMappingEmptyConfig(teamName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "group.#", "0"), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), - ImportStateVerify: true, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, enterprise) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubTeamSyncGroupMappingDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubTeamSyncGroupMappingEmptyConfig(teamName), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "group.#", "0"), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateIdFunc: testAccGithubTeamSyncGroupMappingImportStateIdFunc(rn), + ImportStateVerify: true, + }, }, - }, + }) }) } func testAccCheckGithubTeamSyncGroupMappingDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client - orgName := testAccProvider.Meta().(*Owner).name - ctx := context.TODO() + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName := meta.name + ctx := context.Background() for _, rs := range s.RootModule().Resources { if rs.Type != "github_team_sync_group_mapping" { continue @@ -167,18 +161,22 @@ func testAccCheckGithubTeamSyncGroupMappingDestroy(s *terraform.State) error { return nil } -func testAccCheckGithubTeamSyncGroupMappingDisappears(resourceName string) resource.TestCheckFunc { +func testAccCheckGithubTeamSyncGroupMappingDisappears(ctx context.Context, resourceName string) resource.TestCheckFunc { return func(s *terraform.State) error { rs, ok := s.RootModule().Resources[resourceName] if !ok { return fmt.Errorf("not found: %s", resourceName) } - conn := testAccProvider.Meta().(*Owner).v3client - orgName := testAccProvider.Meta().(*Owner).name + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName := meta.name slug := rs.Primary.Attributes["team_slug"] emptyGroupList := github.IDPGroupList{Groups: []*github.IDPGroup{}} - _, _, err := conn.Teams.CreateOrUpdateIDPGroupConnectionsBySlug(context.TODO(), orgName, slug, emptyGroupList) + _, _, err = conn.Teams.CreateOrUpdateIDPGroupConnectionsBySlug(ctx, orgName, slug, emptyGroupList) return err } diff --git a/github/resource_github_team_test.go b/github/resource_github_team_test.go index e909f5f048..1bf8c62baa 100644 --- a/github/resource_github_team_test.go +++ b/github/resource_github_team_test.go @@ -9,9 +9,8 @@ import ( ) func TestAccGithubTeam(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates a team configured with defaults", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -22,37 +21,20 @@ func TestAccGithubTeam(t *testing.T) { resource.TestCheckResourceAttrSet("github_team.test", "slug"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubTeamHierarchical(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("creates a hierarchy of teams", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "team01" { name = "tf-acc-team01-%s" @@ -109,41 +91,24 @@ func TestAccGithubTeamHierarchical(t *testing.T) { resource.TestCheckResourceAttr("github_team.team03", "parent_team_read_slug", ""), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - Config: config2, - Check: check2, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: config2, + Check: check2, + }, + }, }) }) -} - -func TestAccGithubTeamRemovesDefaultMaintainer(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("creates a team and removes the default maintainer", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -155,37 +120,20 @@ func TestAccGithubTeamRemovesDefaultMaintainer(t *testing.T) { resource.TestCheckResourceAttr("github_team.test", "members_count", "0"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) -} - -func TestAccGithubTeamUpdateName(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) t.Run("marks the slug as computed when the name changes", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) config := fmt.Sprintf(` resource "github_team" "test" { name = "tf-acc-%s" @@ -203,37 +151,23 @@ func TestAccGithubTeamUpdateName(t *testing.T) { } `, randomID, randomID) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_team.test", "slug", fmt.Sprintf("tf-acc-%s", randomID)), - ), - }, - { - Config: configUpdated, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_team.other", "description", fmt.Sprintf("tf-acc-updated-%s", randomID)), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_team.test", "slug", fmt.Sprintf("tf-acc-%s", randomID)), + ), }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - t.Skip("individual account not supported for this operation") - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + Config: configUpdated, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_team.other", "description", fmt.Sprintf("tf-acc-updated-%s", randomID)), + ), + }, + }, }) }) } diff --git a/github/resource_github_user_gpg_key_test.go b/github/resource_github_user_gpg_key_test.go index fdbb6ea663..08b6feeaed 100644 --- a/github/resource_github_user_gpg_key_test.go +++ b/github/resource_github_user_gpg_key_test.go @@ -4,6 +4,7 @@ import ( "fmt" "path/filepath" "regexp" + "strings" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" @@ -11,11 +12,13 @@ import ( func TestAccGithubUserGpgKey(t *testing.T) { t.Run("creates a GPG key without error", func(t *testing.T) { + keyPath := strings.ReplaceAll(filepath.Join("test-fixtures", "gpg-pubkey.asc"), "\\", "/") + config := fmt.Sprintf(` - resource "github_user_gpg_key" "test" { - armored_public_key = "${file("%s")}" - } - `, filepath.Join("test-fixtures", "gpg-pubkey.asc")) + resource "github_user_gpg_key" "test" { + armored_public_key = "${file("%s")}" + } + `, keyPath) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( @@ -30,29 +33,15 @@ func TestAccGithubUserGpgKey(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) } diff --git a/github/resource_github_user_invitation_accepter_test.go b/github/resource_github_user_invitation_accepter_test.go index ae15429873..5b4772fcd6 100644 --- a/github/resource_github_user_invitation_accepter_test.go +++ b/github/resource_github_user_invitation_accepter_test.go @@ -2,61 +2,60 @@ package github import ( "fmt" - "os" "regexp" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/terraform" ) -func TestAccGithubUserInvitationAccepter_basic(t *testing.T) { - rn := "github_repository_collaborator.test" - repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) +func TestAccGithubUserInvitationAccepter(t *testing.T) { + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") + } - inviteeToken := os.Getenv("GITHUB_TEST_COLLABORATOR_TOKEN") - if inviteeToken == "" { - t.Skip("GITHUB_TEST_COLLABORATOR_TOKEN was not provided, skipping test") + if len(testAccConf.testExternalUserToken) == 0 { + t.Skip("No external user token provided") } - var providers []*schema.Provider - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories(&providers), - CheckDestroy: testAccCheckGithubUserInvitationAccepterDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubUserInvitationAccepterConfig(inviteeToken, repoName), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "permission", "push"), - resource.TestMatchResourceAttr(rn, "invitation_id", regexp.MustCompile(`^[0-9]+$`)), - ), + t.Run("accepts an invitation", func(t *testing.T) { + rn := "github_repository_collaborator.test" + repoName := fmt.Sprintf("tf-acc-test-collab-%s", acctest.RandString(5)) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubUserInvitationAccepterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubUserInvitationAccepterConfig(testAccConf.testExternalUserToken, repoName, testAccConf.testExternalUser), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "permission", "push"), + resource.TestMatchResourceAttr(rn, "invitation_id", regexp.MustCompile(`^[0-9]+$`)), + ), + }, }, - }, + }) }) -} -func TestAccGithubUserInvitationAccepterAllowEmptyId(t *testing.T) { - rn := "github_user_invitation_accepter.test" - - var providers []*schema.Provider - - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - ProviderFactories: testAccProviderFactories(&providers), - CheckDestroy: testAccCheckGithubUserInvitationAccepterDestroy, - Steps: []resource.TestStep{ - { - Config: testAccGithubUserInvitationAccepterAllowEmptyId(), - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(rn, "invitation_id", ""), - resource.TestCheckResourceAttr(rn, "allow_empty_id", "true"), - ), + t.Run("accepts an invitation with an empty invitation_id", func(t *testing.T) { + rn := "github_user_invitation_accepter.test" + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccCheckGithubUserInvitationAccepterDestroy, + Steps: []resource.TestStep{ + { + Config: testAccGithubUserInvitationAccepterAllowEmptyId(), + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr(rn, "invitation_id", ""), + resource.TestCheckResourceAttr(rn, "allow_empty_id", "true"), + ), + }, }, - }, + }) }) } @@ -64,7 +63,7 @@ func testAccCheckGithubUserInvitationAccepterDestroy(s *terraform.State) error { return nil } -func testAccGithubUserInvitationAccepterConfig(inviteeToken, repoName string) string { +func testAccGithubUserInvitationAccepterConfig(inviteeToken, repoName, collaborator string) string { return fmt.Sprintf(` provider "github" { alias = "main" @@ -91,7 +90,7 @@ resource "github_user_invitation_accepter" "test" { provider = "github.invitee" invitation_id = "${github_repository_collaborator.test.invitation_id}" } -`, inviteeToken, repoName, testCollaborator) +`, inviteeToken, repoName, collaborator) } func testAccGithubUserInvitationAccepterAllowEmptyId() string { diff --git a/github/resource_github_user_ssh_key_test.go b/github/resource_github_user_ssh_key_test.go index 565929f0b2..80ab315b79 100644 --- a/github/resource_github_user_ssh_key_test.go +++ b/github/resource_github_user_ssh_key_test.go @@ -14,10 +14,9 @@ import ( ) func TestAccGithubUserSshKey(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - testKey := newTestKey() - t.Run("creates and destroys a user SSH key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testKey := newTestKey() config := fmt.Sprintf(` resource "github_user_ssh_key" "test" { title = "tf-acc-test-%s" @@ -40,33 +39,21 @@ func TestAccGithubUserSshKey(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) t.Run("imports an individual account SSH key without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testKey := newTestKey() config := fmt.Sprintf(` resource "github_user_ssh_key" "test" { title = "tf-acc-test-%s" @@ -79,34 +66,20 @@ func TestAccGithubUserSshKey(t *testing.T) { resource.TestCheckResourceAttrSet("github_user_ssh_key.test", "key"), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_user_ssh_key.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_user_ssh_key.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_github_workflow_repository_permissions_test.go b/github/resource_github_workflow_repository_permissions_test.go index 7d06498273..4d7878d789 100644 --- a/github/resource_github_workflow_repository_permissions_test.go +++ b/github/resource_github_workflow_repository_permissions_test.go @@ -32,29 +32,15 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + }, }) }) @@ -87,34 +73,20 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { ), ) - testCase := func(t *testing.T, mode string) { - resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, mode) }, - Providers: testAccProviders, - Steps: []resource.TestStep{ - { - Config: config, - Check: check, - }, - { - ResourceName: "github_workflow_repository_permissions.test", - ImportState: true, - ImportStateVerify: true, - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, }, - }) - } - - t.Run("with an anonymous account", func(t *testing.T) { - t.Skip("anonymous account not supported for this operation") - }) - - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) - - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + { + ResourceName: "github_workflow_repository_permissions.test", + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } diff --git a/github/resource_organization_block_test.go b/github/resource_organization_block_test.go index f4bfb03a62..0f54247d86 100644 --- a/github/resource_organization_block_test.go +++ b/github/resource_organization_block_test.go @@ -10,35 +10,43 @@ import ( ) func TestAccOrganizationBlock_basic(t *testing.T) { - if err := testAccCheckOrganization(); err != nil { - t.Skipf("Skipping because %s.", err.Error()) - } + t.Run("creates organization block", func(t *testing.T) { + config := ` +resource "github_organization_block" "test" { + username = "cgriggs01" +} +` - rn := "github_organization_block.test" + rn := "github_organization_block.test" - resource.ParallelTest(t, resource.TestCase{ - PreCheck: func() { testAccPreCheck(t) }, - Providers: testAccProviders, - CheckDestroy: testAccOrganizationBlockDestroy, - Steps: []resource.TestStep{ - { - Config: testAccOrganizationBlockConfig, - Check: resource.ComposeTestCheckFunc( - testAccCheckOrganizationBlockExists(rn), - ), - }, - { - ResourceName: rn, - ImportState: true, - ImportStateVerify: true, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessHasOrgs(t) }, + ProviderFactories: providerFactories, + CheckDestroy: testAccOrganizationBlockDestroy, + Steps: []resource.TestStep{ + { + Config: config, + Check: resource.ComposeTestCheckFunc( + testAccCheckOrganizationBlockExists(rn), + ), + }, + { + ResourceName: rn, + ImportState: true, + ImportStateVerify: true, + }, }, - }, + }) }) } func testAccOrganizationBlockDestroy(s *terraform.State) error { - conn := testAccProvider.Meta().(*Owner).v3client - orgName := testAccProvider.Meta().(*Owner).name + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName := meta.name for _, rs := range s.RootModule().Resources { if rs.Type != "github_organization_block" { @@ -47,7 +55,7 @@ func testAccOrganizationBlockDestroy(s *terraform.State) error { username := rs.Primary.ID - res, err := conn.Organizations.UnblockUser(context.TODO(), orgName, username) + res, err := conn.Organizations.UnblockUser(context.Background(), orgName, username) if res.StatusCode != 404 { return err } @@ -64,10 +72,14 @@ func testAccCheckOrganizationBlockExists(n string) resource.TestCheckFunc { } username := rs.Primary.ID - conn := testAccProvider.Meta().(*Owner).v3client - orgName := testAccProvider.Meta().(*Owner).name + meta, err := getTestMeta() + if err != nil { + return err + } + conn := meta.v3client + orgName := meta.name - blocked, _, err := conn.Organizations.IsBlocked(context.TODO(), orgName, username) + blocked, _, err := conn.Organizations.IsBlocked(context.Background(), orgName, username) if err != nil { return err } @@ -77,9 +89,3 @@ func testAccCheckOrganizationBlockExists(n string) resource.TestCheckFunc { return nil } } - -const testAccOrganizationBlockConfig = ` -resource "github_organization_block" "test" { - username = "cgriggs01" -} -` diff --git a/github/sweeper_test.go b/github/sweeper_test.go deleted file mode 100644 index 9aa05379c1..0000000000 --- a/github/sweeper_test.go +++ /dev/null @@ -1,36 +0,0 @@ -package github - -import ( - "fmt" - "os" - "testing" - - "github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource" -) - -func TestMain(m *testing.M) { - resource.TestMain(m) -} - -func sharedConfigForRegion() (any, error) { - if os.Getenv("GITHUB_TOKEN") == "" { - return nil, fmt.Errorf("empty GITHUB_TOKEN") - } - - if os.Getenv("GITHUB_OWNER") == "" { - return nil, fmt.Errorf("empty GITHUB_OWNER") - } - - config := Config{ - Token: os.Getenv("GITHUB_TOKEN"), - Owner: os.Getenv("GITHUB_OWNER"), - BaseURL: "", - } - - meta, err := config.Meta() - if err != nil { - return nil, fmt.Errorf("error getting GitHub meta parameter") - } - - return meta, nil -} diff --git a/github/test-fixtures/README.md b/github/test-fixtures/README.md index 89a01e9691..e55c27fed7 100644 --- a/github/test-fixtures/README.md +++ b/github/test-fixtures/README.md @@ -1,4 +1,4 @@ -# Hi fellow bots and humans :wave: +# Hi fellow bots and humans :wave If you're about to panic about leaked private keys, then please don't. These are purposefully exposed cryptographic materials used in tests of @@ -7,6 +7,7 @@ the GitHub provider. Thanks for understanding :heart: ## Self-Signed Certificate (cert.pem, domain.csr, key.pem) + A self-signed cert & key used in acceptance tests of the GitHub provider. Generated via: @@ -32,11 +33,8 @@ openssl x509 \ ``` ## GPG Key (gpg-pubkey.asc) -Terraform's acceptance tests GPG public key. - -## SSH Public Key (id_rsa.pub) -Terraform's acceptance tests SSH public key. +Terraform's acceptance tests GPG public key. ## GitHub App Keys (github-app-key.pem, github-app-key.pub) @@ -44,7 +42,7 @@ Terraform's acceptance tests GitHub App public and private key. You can re-generate them by using the following commands: -``` +```text # Private Key openssl rsa -in github-app-key.pem -pubout -outform PEM diff --git a/github/test-fixtures/id_rsa.pub b/github/test-fixtures/id_rsa.pub deleted file mode 100644 index 0a763e43f7..0000000000 --- a/github/test-fixtures/id_rsa.pub +++ /dev/null @@ -1 +0,0 @@ -ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQDnDk1liOxXwE27fjOVVHl6RNVgQznGqGIfhsoa5QNfLOcoWJR3EIv44dSUx1GSvxQ7uR9qBY/i/SEdAbKdupo3Ru5sykc0GqaMRVys+Cin/Lgnl6+ntmTZOudNjIbz10Vfu/dKmexSzqlD3XWzPGXRI5WyKWzvc2XKjRdfnOOzogJpqJ5kh/CN0ZhCzBPTu/b4mJl2ionTEzEeLK2g4Re4IuU/dGoyf0LGLidjmqhSY7dQtL+mfte9m3x/BQTrDf0+AW3kGWXR8EL0EyIJ2HRtHW67YnoOcTAFK0hDCuKgvt78rqdUQ2bVjcsIhNqnvQMPf3ZeZ5bP2JqB9zKaFl8uaRJv+TdxEeFTkgnbYb85M+aBggBYr6xxeb24g7WlU0iPxJ8GmjvCizxe2I1DOJDRDozn1sinKjapNRdJy00iuo46TJC5Wgmid0vnMJ7SMZtubz+btxhoFLt4F4U2JnILaYG4/buJg4H/GkqmkE8G3hr4b4mgsFXBtBFgK6uCTFQSvvV7TyyWkZxHL6DRCxL/Dp0bSj+EM8Tw1K304EvkBEO3rMyvPs4nXL7pepyKWalmUI8U4Qp2xMXSq7fmfZY55osb03MUAtKl0wJ/ykyKOwYWeLbubSVcc6VPx5bXZmnM5bTcZdYW9+vNt86X2F2b0h/sIkGNEPpqQQBzElY+fQ== terraform-acctest@hashicorp.com diff --git a/github/util_test.go b/github/util_test.go index 10af1b49a6..5dbd9374fe 100644 --- a/github/util_test.go +++ b/github/util_test.go @@ -7,7 +7,7 @@ import ( "github.com/hashicorp/go-cty/cty" ) -func TestAccGithubUtilRole_validation(t *testing.T) { +func TestGithubUtilRole_validation(t *testing.T) { cases := []struct { Value string ErrCount int @@ -37,7 +37,7 @@ func TestAccGithubUtilRole_validation(t *testing.T) { } } -func TestAccGithubUtilTwoPartID(t *testing.T) { +func TestGithubUtilTwoPartID(t *testing.T) { partOne, partTwo := "foo", "bar" id := buildTwoPartID(partOne, partTwo) @@ -77,7 +77,7 @@ func flipUsernameCase(username string) string { return string(oc) } -func TestAccGithubUtilValidateSecretName(t *testing.T) { +func TestGithubUtilValidateSecretName(t *testing.T) { cases := []struct { Name string Error bool diff --git a/scripts/gofmtcheck.sh b/scripts/gofmtcheck.sh deleted file mode 100755 index 1c055815f8..0000000000 --- a/scripts/gofmtcheck.sh +++ /dev/null @@ -1,13 +0,0 @@ -#!/usr/bin/env bash - -# Check gofmt -echo "==> Checking that code complies with gofmt requirements..." -gofmt_files=$(gofmt -l `find . -name '*.go' | grep -v vendor`) -if [[ -n ${gofmt_files} ]]; then - echo 'gofmt needs running on the following files:' - echo "${gofmt_files}" - echo "You can use the command: \`make fmt\` to reformat code." - exit 1 -fi - -exit 0