diff --git a/.github/workflows/ci.yaml b/.github/workflows/ci.yaml index 123a0dd612..a01131a0c0 100644 --- a/.github/workflows/ci.yaml +++ b/.github/workflows/ci.yaml @@ -14,8 +14,7 @@ concurrency: group: ci-${{ github.ref }} cancel-in-progress: true -permissions: - contents: read # for actions/checkout +permissions: read-all jobs: ci: 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..bbdda9c93a 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 @@ -29,7 +34,8 @@ jobs: strategy: matrix: mode: [anonymous, individual, organization] # team, enterprise - fail-fast: false + fail-fast: true + max-parallel: 1 defaults: run: shell: bash @@ -38,8 +44,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 +61,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 +78,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 c5fd2e833a..4c13747381 100644 --- a/GNUmakefile +++ b/GNUmakefile @@ -1,7 +1,9 @@ -TEST?=$$(go list ./... |grep -v 'vendor') +SWEEP?=repositories,teams WEBSITE_REPO=github.com/hashicorp/terraform-website PKG_NAME=github +export TESTARGS=-race -coverprofile=coverage.txt -covermode=atomic + default: build tools: @@ -12,7 +14,7 @@ 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 ./... lint: @@ -27,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 \ @@ -38,6 +40,10 @@ test-compile: fi CGO_ENABLED=0 go test -c $(TEST) $(TESTARGS) +sweep: + @echo "WARNING: This will destroy infrastructure. Use only in development accounts." + go test $(TEST) -v -sweep=$(SWEEP) $(SWEEPARGS) + website: ifeq (,$(wildcard $(GOPATH)/src/$(WEBSITE_REPO))) echo "$(WEBSITE_REPO) not found in your GOPATH (necessary for layouts and assets), get-ting..." @@ -56,4 +62,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 lint lintcheck tools test-compile website website-lint website-test +.PHONY: build test testacc fmt lint lintcheck tools test-compile website website-lint website-test sweep diff --git a/github/acc_test.go b/github/acc_test.go new file mode 100644 index 0000000000..ea6e35f4fd --- /dev/null +++ b/github/acc_test.go @@ -0,0 +1,291 @@ +package github + +import ( + "context" + "fmt" + "net/url" + "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 = "tf-acc-test-" + +var ( + orgTestModes = []testMode{organization, team, enterprise} + paidOrgTestModes = []testMode{team, enterprise} +) + +type testAccConfig struct { + // Target configuration + baseURL *url.URL + + // 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 + } + + u, ok := os.LookupEnv("GITHUB_BASE_URL") + if !ok { + u = DotComAPIURL + } + + baseURL, err := url.Parse(u) + if err != nil { + fmt.Printf("Error parsing base URL: %s\n", err) + os.Exit(1) + } + + 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 e72bc35e60..67d6223031 100644 --- a/github/config_test.go +++ b/github/config_test.go @@ -157,11 +157,6 @@ func Test_getBaseURL(t *testing.T) { } func TestAccConfigMeta(t *testing.T) { - // FIXME: Skip test runs during travis lint checking - if testToken == "" { - return - } - baseURL, _, err := getBaseURL(DotComAPIURL) if err != nil { t.Fatalf("failed to parse test base URL: %s", err.Error()) @@ -183,8 +178,10 @@ func TestAccConfigMeta(t *testing.T) { }) 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: baseURL, } meta, err := config.Meta() @@ -201,8 +198,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: baseURL, RetryableErrors: map[int]bool{ 500: true, @@ -224,8 +223,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: baseURL, } meta, err := config.Meta() @@ -246,10 +247,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: baseURL, - Owner: testOrganization, + Owner: testAccConf.owner, } meta, err := config.Meta() if err != nil { @@ -258,17 +261,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: baseURL, - Owner: testOrganization, + Owner: testAccConf.owner, } meta, err := config.Meta() if err != nil { @@ -283,7 +288,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..384cbbcbfb 100644 --- a/github/data_source_github_actions_environment_public_key_test.go +++ b/github/data_source_github_actions_environment_public_key_test.go @@ -9,24 +9,25 @@ 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) + repoName := fmt.Sprintf("%srepo-env-pubkey-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } resource "github_repository_environment" "test" { repository = github_repository.test.name - environment = "tf-acc-test-%[1]s" + environment = "tf-acc-test-%[2]s" } data "github_actions_environment_public_key" "test" { repository = github_repository.test.name environment = github_repository_environment.test.environment - }`, randomID) + }`, repoName, randomID) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -34,29 +35,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..0e960aa8f4 100644 --- a/github/data_source_github_actions_environment_secrets_test.go +++ b/github/data_source_github_actions_environment_secrets_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubActionsEnvironmentSecretsDataSource(t *testing.T) { t.Run("queries actions secrets from an environment", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-secrets-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -29,7 +30,7 @@ func TestAccGithubActionsEnvironmentSecretsDataSource(t *testing.T) { repository = github_repository.test.name plaintext_value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_actions_environment_secrets" "test" { @@ -39,32 +40,26 @@ func TestAccGithubActionsEnvironmentSecretsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_actions_environment_secrets.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_actions_environment_secrets.test", "name", repoName), resource.TestCheckResourceAttr("data.github_actions_environment_secrets.test", "secrets.#", "1"), resource.TestCheckResourceAttr("data.github_actions_environment_secrets.test", "secrets.0.name", "SECRET_1"), resource.TestCheckResourceAttrSet("data.github_actions_environment_secrets.test", "secrets.0.created_at"), 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..b41170bac9 100644 --- a/github/data_source_github_actions_environment_variables_test.go +++ b/github/data_source_github_actions_environment_variables_test.go @@ -12,10 +12,11 @@ import ( func TestAccGithubActionsEnvironmentVariablesDataSource(t *testing.T) { t.Run("queries actions variables from an environment", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-vars-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -29,7 +30,7 @@ func TestAccGithubActionsEnvironmentVariablesDataSource(t *testing.T) { variable_name = "test_variable" value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_actions_environment_variables" "test" { @@ -46,25 +47,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..2217dbe539 100644 --- a/github/data_source_github_actions_organization_secrets_test.go +++ b/github/data_source_github_actions_organization_secrets_test.go @@ -27,32 +27,26 @@ func TestAccGithubActionsOrganizationSecretsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_actions_organization_secrets.test", "secrets.#", "1"), - resource.TestCheckResourceAttr("data.github_actions_organization_secrets.test", "secrets.0.name", strings.ToUpper(fmt.Sprintf("ORG_SECRET_1_%s", randomID))), - resource.TestCheckResourceAttr("data.github_actions_organization_secrets.test", "secrets.0.visibility", "all"), + // resource.TestCheckResourceAttr("data.github_actions_organization_secrets.test", "secrets.#", "1"), // There is no feasible way to know how many secrets exist in the Org during test runs. And I couldn't find a "greater than" operator + resource.TestCheckTypeSetElemAttr("data.github_actions_organization_secrets.test", "secrets.*.*", strings.ToUpper(fmt.Sprintf("ORG_SECRET_1_%s", randomID))), + resource.TestCheckTypeSetElemAttr("data.github_actions_organization_secrets.test", "secrets.*.*", "all"), resource.TestCheckResourceAttrSet("data.github_actions_organization_secrets.test", "secrets.0.created_at"), 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..cd05217215 100644 --- a/github/data_source_github_actions_public_key_test.go +++ b/github/data_source_github_actions_public_key_test.go @@ -10,18 +10,19 @@ import ( func TestAccGithubActionsPublicKeyDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-actions-pubkey-%s", testResourcePrefix, randomID) t.Run("queries a repository public key without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_actions_public_key" "test" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -29,29 +30,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..c4c53cb892 100644 --- a/github/data_source_github_actions_registration_token_test.go +++ b/github/data_source_github_actions_registration_token_test.go @@ -10,48 +10,35 @@ import ( func TestAccGithubActionsRegistrationTokenDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-actions-regtoken-%s", testResourcePrefix, randomID) t.Run("get a repository registration token without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_actions_registration_token" "test" { repository = github_repository.test.id } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_actions_registration_token.test", "repository", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_actions_registration_token.test", "repository", repoName), resource.TestCheckResourceAttrSet("data.github_actions_registration_token.test", "token"), 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..6fec7776b4 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 @@ -10,20 +10,21 @@ import ( func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplateDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-oidc-%s", testResourcePrefix, randomID) t.Run("get an repository oidc subject claim customization template without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } - + resource "github_actions_repository_oidc_subject_claim_customization_template" "test" { repository = github_repository.test.name use_default = false include_claim_keys = ["repo", "context", "job_workflow_ref"] } - `, randomID) + `, repoName) config2 := config + ` data "github_actions_repository_oidc_subject_claim_customization_template" "test" { @@ -33,15 +34,15 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplateDataSour config3 := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } - + resource "github_actions_repository_oidc_subject_claim_customization_template" "test" { repository = github_repository.test.name use_default = true } - `, randomID) + `, repoName) config4 := config3 + ` data "github_actions_repository_oidc_subject_claim_customization_template" "test" { @@ -62,41 +63,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..c07a81be04 100644 --- a/github/data_source_github_actions_secrets_test.go +++ b/github/data_source_github_actions_secrets_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubActionsSecretsDataSource(t *testing.T) { t.Run("queries actions secrets from a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-actions-secrets-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -23,7 +24,7 @@ func TestAccGithubActionsSecretsDataSource(t *testing.T) { repository = github_repository.test.name plaintext_value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_actions_secrets" "test" { @@ -32,32 +33,26 @@ func TestAccGithubActionsSecretsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_actions_secrets.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_actions_secrets.test", "name", repoName), resource.TestCheckResourceAttr("data.github_actions_secrets.test", "secrets.#", "1"), resource.TestCheckResourceAttr("data.github_actions_secrets.test", "secrets.0.name", "SECRET_1"), resource.TestCheckResourceAttrSet("data.github_actions_secrets.test", "secrets.0.created_at"), 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..370fa38e52 100644 --- a/github/data_source_github_actions_variables_test.go +++ b/github/data_source_github_actions_variables_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubActionsVariablesDataSource(t *testing.T) { t.Run("queries actions variables from a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-actions-vars-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -23,7 +24,7 @@ func TestAccGithubActionsVariablesDataSource(t *testing.T) { repository = github_repository.test.name value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_actions_variables" "test" { @@ -32,7 +33,7 @@ func TestAccGithubActionsVariablesDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_actions_variables.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_actions_variables.test", "name", repoName), resource.TestCheckResourceAttr("data.github_actions_variables.test", "variables.#", "1"), resource.TestCheckResourceAttr("data.github_actions_variables.test", "variables.0.name", "VARIABLE_1"), resource.TestCheckResourceAttr("data.github_actions_variables.test", "variables.0.value", "foo"), @@ -40,25 +41,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 2c47f3b4c1..18effee268 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("/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 0aadf10d44..7cf016098b 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 { var ghErr *github.ErrorResponse if errors.As(err, &ghErr) { diff --git a/github/data_source_github_branch_protection_rules_test.go b/github/data_source_github_branch_protection_rules_test.go index c2545923bf..df7138b636 100644 --- a/github/data_source_github_branch_protection_rules_test.go +++ b/github/data_source_github_branch_protection_rules_test.go @@ -11,54 +11,42 @@ import ( func TestAccGithubBranchProtectionRulesDataSource(t *testing.T) { t.Run("queries branch protection rules without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-bp-rules-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_branch_protection_rules" "all" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( 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) + }, }) }) t.Run("queries branch protection", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-bp-rules2-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } @@ -66,7 +54,7 @@ func TestAccGithubBranchProtectionRulesDataSource(t *testing.T) { repository_id = github_repository.test.name pattern = "main*" } - `, randomID) + `, repoName) config2 := config + ` data "github_branch_protection_rules" "all" { @@ -79,32 +67,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..8be51e858e 100644 --- a/github/data_source_github_branch_test.go +++ b/github/data_source_github_branch_test.go @@ -12,10 +12,11 @@ import ( func TestAccGithubBranchDataSource(t *testing.T) { t.Run("queries an existing branch without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-branch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } @@ -23,7 +24,7 @@ func TestAccGithubBranchDataSource(t *testing.T) { repository = github_repository.test.name branch = "main" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( @@ -31,76 +32,50 @@ 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) + // repoName := fmt.Sprintf("%sinvalid-branch-%s", testResourcePrefix, randomID) + + // config := fmt.Sprintf(` + // resource "github_repository" "test" { + // name = "%s" + // auto_init = true + // } + + // data "github_branch" "test" { + // repository = github_repository.test.name + // branch = "xxxxxx" + // } + // `, repoName) + + // 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..85dd76394d 100644 --- a/github/data_source_github_codespaces_public_key_test.go +++ b/github/data_source_github_codespaces_public_key_test.go @@ -10,18 +10,19 @@ import ( func TestAccGithubCodespacesPublicKeyDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-cs-pubkey-%s", testResourcePrefix, randomID) t.Run("queries a repository public key without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_codespaces_public_key" "test" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -29,29 +30,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..c71a90270f 100644 --- a/github/data_source_github_codespaces_secrets_test.go +++ b/github/data_source_github_codespaces_secrets_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubCodespacesSecretsDataSource(t *testing.T) { t.Run("queries codespaces secrets from a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-cs-secrets-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -23,7 +24,7 @@ func TestAccGithubCodespacesSecretsDataSource(t *testing.T) { repository = github_repository.test.name plaintext_value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_codespaces_secrets" "test" { @@ -32,40 +33,26 @@ func TestAccGithubCodespacesSecretsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_codespaces_secrets.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_codespaces_secrets.test", "name", repoName), resource.TestCheckResourceAttr("data.github_codespaces_secrets.test", "secrets.#", "1"), resource.TestCheckResourceAttr("data.github_codespaces_secrets.test", "secrets.0.name", "CS_SECRET_1"), resource.TestCheckResourceAttrSet("data.github_codespaces_secrets.test", "secrets.0.created_at"), 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..d7733331a1 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("%srepo-collab-%s", testResourcePrefix, 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("%srepo-collab-%s", testResourcePrefix, 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..6da9b92e5d 100644 --- a/github/data_source_github_dependabot_public_key_test.go +++ b/github/data_source_github_dependabot_public_key_test.go @@ -10,18 +10,19 @@ import ( func TestAccGithubDependabotPublicKeyDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-dep-pubkey-%s", testResourcePrefix, randomID) t.Run("queries a repository public key without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_actions_public_key" "test" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -29,29 +30,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..694d0c422b 100644 --- a/github/data_source_github_dependabot_secrets_test.go +++ b/github/data_source_github_dependabot_secrets_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubDependabotSecretsDataSource(t *testing.T) { t.Run("queries dependabot secrets from a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-dep-secrets-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -23,7 +24,7 @@ func TestAccGithubDependabotSecretsDataSource(t *testing.T) { repository = github_repository.test.name plaintext_value = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_dependabot_secrets" "test" { @@ -32,32 +33,26 @@ func TestAccGithubDependabotSecretsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_dependabot_secrets.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_dependabot_secrets.test", "name", repoName), resource.TestCheckResourceAttr("data.github_dependabot_secrets.test", "secrets.#", "1"), resource.TestCheckResourceAttr("data.github_dependabot_secrets.test", "secrets.0.name", "DEP_SECRET_1"), resource.TestCheckResourceAttrSet("data.github_dependabot_secrets.test", "secrets.0.created_at"), 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..c03b48493c 100644 --- a/github/data_source_github_issue_labels_test.go +++ b/github/data_source_github_issue_labels_test.go @@ -12,16 +12,17 @@ import ( func TestAccGithubIssueLabelsDataSource(t *testing.T) { t.Run("queries the labels for a repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-issue-labels-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_issue_labels" "test" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( @@ -29,29 +30,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 0d0ebedb49..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{ - "team_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 7d891f3193..5ce65b1682 100644 --- a/github/data_source_github_organization_role_teams_test.go +++ b/github/data_source_github_organization_role_teams_test.go @@ -11,7 +11,7 @@ import ( func TestAccDataSourceGithubOrganizationRoleTeams(t *testing.T) { t.Run("get the organization role teams without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - teamName := fmt.Sprintf("tf-acc-team-%s", randomID) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) roleId := 8134 config := fmt.Sprintf(` resource "github_team" "test" { @@ -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{ { @@ -41,7 +41,7 @@ func TestAccDataSourceGithubOrganizationRoleTeams(t *testing.T) { Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_organization_role_teams.test", "teams.#"), resource.TestCheckResourceAttr("data.github_organization_role_teams.test", "teams.#", "1"), - resource.TestCheckResourceAttrPair("data.github_organization_role_teams.test", "teams.0.team_id", "github_team.test", "team_id"), + resource.TestCheckResourceAttrPair("data.github_organization_role_teams.test", "teams.0.team_id", "github_team.test", "id"), resource.TestCheckResourceAttrPair("data.github_organization_role_teams.test", "teams.0.slug", "github_team.test", "slug"), resource.TestCheckResourceAttrPair("data.github_organization_role_teams.test", "teams.0.name", "github_team.test", "name"), ), @@ -52,8 +52,8 @@ func TestAccDataSourceGithubOrganizationRoleTeams(t *testing.T) { t.Run("get indirect organization role teams without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - teamName1 := fmt.Sprintf("tf-acc-team-1-%s", randomID) - teamName2 := fmt.Sprintf("tf-acc-team-2-%s", randomID) + teamName1 := fmt.Sprintf("%steam-1-%s", testResourcePrefix, randomID) + teamName2 := fmt.Sprintf("%steam-2-%s", testResourcePrefix, randomID) roleId := 8134 config := fmt.Sprintf(` resource "github_team" "test_1" { @@ -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 80d225b948..d795218051 100644 --- a/github/data_source_github_organization_role_users.go +++ b/github/data_source_github_organization_role_users.go @@ -82,7 +82,7 @@ func dataSourceGithubOrganizationRoleUsersRead(ctx context.Context, d *schema.Re for _, user := range users { u := map[string]any{ - "user_id": user.GetID(), + "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..895d2380d7 100644 --- a/github/data_source_github_organization_role_users_test.go +++ b/github/data_source_github_organization_role_users_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "testing" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest" @@ -10,11 +9,6 @@ import ( ) func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { - login := os.Getenv("GITHUB_IN_ORG_USER") - if len(login) == 0 { - t.Skip("set inOrgUser to unskip this test run") - } - t.Run("get the organization role users without error", func(t *testing.T) { roleId := 8134 config := fmt.Sprintf(` @@ -30,10 +24,10 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { github_organization_role_user.test ] } - `, roleId, login) + `, roleId, testAccConf.testOrgUser) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -42,7 +36,7 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_organization_role_users.test", "users.#"), resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.#", "1"), resource.TestCheckResourceAttrSet("data.github_organization_role_users.test", "users.0.user_id"), - resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.0.login", login), + resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.0.login", testAccConf.testOrgUser), ), }, }, @@ -51,7 +45,7 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { t.Run("get indirect organization role users without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - teamName := fmt.Sprintf("tf-acc-team-%s", randomID) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) roleId := 8134 config := fmt.Sprintf(` resource "github_team" "test" { @@ -76,10 +70,10 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { github_organization_role_team.test ] } - `, teamName, login, roleId) + `, teamName, testAccConf.testOrgUser, roleId) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { @@ -88,7 +82,7 @@ func TestAccDataSourceGithubOrganizationRoleUsers(t *testing.T) { resource.TestCheckResourceAttrSet("data.github_organization_role_users.test", "users.#"), resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.#", "1"), resource.TestCheckResourceAttrSet("data.github_organization_role_users.test", "users.0.user_id"), - resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.0.login", login), + resource.TestCheckResourceAttr("data.github_organization_role_users.test", "users.0.login", testAccConf.testOrgUser), ), }, }, 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..0fa0a60500 100644 --- a/github/data_source_github_organization_security_managers_test.go +++ b/github/data_source_github_organization_security_managers_test.go @@ -11,7 +11,7 @@ import ( func TestAccDataSourceGithubOrganizationSecurityManagers(t *testing.T) { t.Run("get the organization security managers without error", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - teamName := fmt.Sprintf("tf-acc-%s", randomID) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { @@ -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..31d082283c 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("%steam-0-%s", testResourcePrefix, 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..f9d4f0a5c1 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,38 +43,25 @@ 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) + }, }) }) t.Run("queries for an organization with archived repos", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-archived-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "archived" { - name = "tf-acc-archived-%s" + name = "%s" archived = true } @@ -94,43 +79,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) + `, repoName, 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 +111,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 +140,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 69551f5830..b432f9b95c 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 { var ghErr *github.ErrorResponse if errors.As(err, &ghErr) { diff --git a/github/data_source_github_ref_test.go b/github/data_source_github_ref_test.go index 7ad3b6317f..f5f5dc8def 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,96 +9,67 @@ 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) + repoName := fmt.Sprintf("%srepo-ref-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } 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, - }, + `, repoName, 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 0fe967ed23..818de73e73 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 { var ghErr *github.ErrorResponse if errors.As(err, &ghErr) { @@ -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..54261ec959 100644 --- a/github/data_source_github_repository_autolink_references_test.go +++ b/github/data_source_github_repository_autolink_references_test.go @@ -10,11 +10,12 @@ import ( func TestAccGithubRepositoryAutolinkReferencesDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-autolink-refs-%s", testResourcePrefix, randomID) t.Run("queries autolink references", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } @@ -24,7 +25,7 @@ func TestAccGithubRepositoryAutolinkReferencesDataSource(t *testing.T) { key_prefix = "TEST1-" target_url_template = "https://example.com/TEST-" } - `, randomID) + `, repoName) config2 := config + ` data "github_repository_autolink_references" "all" { @@ -38,32 +39,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..55cfd86cbb 100644 --- a/github/data_source_github_repository_branches_test.go +++ b/github/data_source_github_repository_branches_test.go @@ -10,7 +10,7 @@ import ( func TestAccGithubRepositoryBranchesDataSource(t *testing.T) { t.Run("manages branches of a new repository", func(t *testing.T) { - repoName := fmt.Sprintf("tf-acc-test-branches-%s", acctest.RandString(5)) + repoName := fmt.Sprintf("%srepo-branches-%s", testResourcePrefix, acctest.RandString(5)) config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" @@ -29,34 +29,20 @@ 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) + }, }) }) t.Run("manages branches of a new repository with filtering", func(t *testing.T) { - repoName := fmt.Sprintf("tf-acc-test-branches-%s", acctest.RandString(5)) + repoName := fmt.Sprintf("%srepo-branches-%s", testResourcePrefix, acctest.RandString(5)) config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" @@ -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..29da0d447a 100644 --- a/github/data_source_github_repository_custom_properties_test.go +++ b/github/data_source_github_repository_custom_properties_test.go @@ -9,220 +9,190 @@ 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) + repoName := fmt.Sprintf("%srepo-custom-props-%s", testResourcePrefix, 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-props-%s", testResourcePrefix, 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-props-%s", testResourcePrefix, 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-props-%s", testResourcePrefix, 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" + name = "%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, repoName) 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..dab6d610bd 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") - - 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 - } - ` + 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) + } - 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"), - ) + keyPath := strings.ReplaceAll(filepath.Join("test-fixtures", fmt.Sprintf("%s.pub", keyName)), "\\", "/") - testCase := 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, - }, - }, - }) + repoName := fmt.Sprintf("%srepo-deploy-keys-%s", testResourcePrefix, acctest.RandString(5)) + config := fmt.Sprintf(` + 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..2c1e1a251d 100644 --- a/github/data_source_github_repository_deployment_branch_policies_test.go +++ b/github/data_source_github_repository_deployment_branch_policies_test.go @@ -9,12 +9,12 @@ 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) + repoName := fmt.Sprintf("%srepo-deploy-bp-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -32,7 +32,7 @@ func TestAccGithubRepositoryDeploymentBranchPolicies(t *testing.T) { environment_name = github_repository_environment.env.environment name = "foo" } - `, randomID) + `, repoName) config2 := config + ` data "github_repository_deployment_branch_policies" "all" { @@ -46,32 +46,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_test.go b/github/data_source_github_repository_environment_deployment_policies_test.go index 539e8d2a93..0e3c003c15 100644 --- a/github/data_source_github_repository_environment_deployment_policies_test.go +++ b/github/data_source_github_repository_environment_deployment_policies_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubRepositoryEnvironmentDeploymentPolicies(t *testing.T) { t.Run("queries environment deployment policies", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-pol-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -45,40 +46,26 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicies(t *testing.T) { depends_on = [github_repository_environment_deployment_policy.branch, github_repository_environment_deployment_policy.tag] } - `, randomID) + `, repoName) - 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: config, - Check: resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.#", "2"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.0.type", "branch"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.0.pattern", "foo"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.1.type", "tag"), - resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.1.pattern", "bar"), - ), - }, + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + 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: config, + Check: resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.#", "2"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.0.type", "branch"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.0.pattern", "foo"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.1.type", "tag"), + resource.TestCheckResourceAttr("data.github_repository_environment_deployment_policies.test", "policies.1.pattern", "bar"), + ), + }, + }, }) }) } diff --git a/github/data_source_github_repository_environments_test.go b/github/data_source_github_repository_environments_test.go index 0c43350807..e7171011a9 100644 --- a/github/data_source_github_repository_environments_test.go +++ b/github/data_source_github_repository_environments_test.go @@ -10,18 +10,19 @@ import ( func TestAccGithubRepositoryEnvironmentsDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-envs-%s", testResourcePrefix, randomID) t.Run("queries environments", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } resource "github_repository_environment" "env1" { repository = github_repository.test.name environment = "env_x" } - `, randomID) + `, repoName) config2 := config + ` data "github_repository_environments" "all" { @@ -34,32 +35,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 e710cb9572..d8545cd9cb 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..27bba16c29 100644 --- a/github/data_source_github_repository_file_test.go +++ b/github/data_source_github_repository_file_test.go @@ -1,32 +1,25 @@ 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) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true + + lifecycle { + ignore_changes = all + } } resource "github_repository_file" "test" { @@ -44,82 +37,99 @@ func TestAccGithubRepositoryFileDataSource(t *testing.T) { branch = "main" file = github_repository_file.test.file } - `, randomID) + `, 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"), + ), + }, + }, + }) + }) - 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", - ), - ) + 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("%srepo-file-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + auto_init = 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, - }, - }, - }) - } + lifecycle { + ignore_changes = all + } + } - t.Run("with an anonymous account", func(t *testing.T) { - testCase(t, anonymous) - }) + 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" + } - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + data "github_repository_file" "test" { + repository = "%[1]s" + branch = "main" + file = github_repository_file.test.file - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + 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) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%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" @@ -131,378 +141,108 @@ func TestAccGithubRepositoryFileDataSource(t *testing.T) { repository = github_repository.test.name file = github_repository_file.test.file } - `, 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, - }, + `, 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.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) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%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, - }, + `, 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.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..485110d9d2 100644 --- a/github/data_source_github_repository_milestone_test.go +++ b/github/data_source_github_repository_milestone_test.go @@ -10,13 +10,13 @@ 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) + repoName := fmt.Sprintf("%srepo-milestone-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_milestone" "test" { @@ -34,7 +34,7 @@ func TestAccGithubRepositoryMilestoneDataSource(t *testing.T) { number = github_repository_milestone.test.number } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -43,29 +43,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..bacdc008a1 100644 --- a/github/data_source_github_repository_pull_request_test.go +++ b/github/data_source_github_repository_pull_request_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubRepositoryPullRequestDataSource(t *testing.T) { t.Run("manages the pull request lifecycle", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-pr-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -43,14 +44,14 @@ func TestAccGithubRepositoryPullRequestDataSource(t *testing.T) { base_repository = github_repository_pull_request.test.base_repository number = github_repository_pull_request.test.number } - `, randomID) + `, repoName) const resourceName = "data.github_repository_pull_request.test" check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( resourceName, "base_repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr(resourceName, "base_ref", "main"), resource.TestCheckResourceAttr(resourceName, "head_ref", "test"), @@ -68,29 +69,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..7bf4ce6098 100644 --- a/github/data_source_github_repository_pull_requests_test.go +++ b/github/data_source_github_repository_pull_requests_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubRepositoryPullRequestsDataSource(t *testing.T) { t.Run("manages the pull request lifecycle", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-prs-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -47,12 +48,12 @@ func TestAccGithubRepositoryPullRequestsDataSource(t *testing.T) { sort_direction = "desc" state = "open" } - `, randomID) + `, repoName) const resourceName = "data.github_repository_pull_requests.test" check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr(resourceName, "base_repository", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr(resourceName, "base_repository", repoName), resource.TestCheckResourceAttr(resourceName, "state", "open"), resource.TestCheckResourceAttr(resourceName, "base_ref", "main"), resource.TestCheckResourceAttr(resourceName, "head_ref", "test"), @@ -67,7 +68,7 @@ func TestAccGithubRepositoryPullRequestsDataSource(t *testing.T) { resource.TestCheckResourceAttr(resourceName, "results.0.draft", "false"), resource.TestCheckResourceAttrSet(resourceName, "results.0.head_owner"), resource.TestCheckResourceAttr(resourceName, "results.0.head_ref", "test"), - resource.TestCheckResourceAttr(resourceName, "results.0.head_repository", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr(resourceName, "results.0.head_repository", repoName), resource.TestCheckResourceAttrSet(resourceName, "results.0.head_sha"), resource.TestCheckResourceAttr(resourceName, "results.0.labels.#", "0"), resource.TestCheckResourceAttr(resourceName, "results.0.maintainer_can_modify", "false"), @@ -78,29 +79,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..4decdfd3a0 100644 --- a/github/data_source_github_repository_teams_test.go +++ b/github/data_source_github_repository_teams_test.go @@ -11,15 +11,17 @@ import ( func TestAccGithubRepositoryTeamsDataSource(t *testing.T) { t.Run("queries teams of an existing repository", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_team_repository" "test" { @@ -27,7 +29,7 @@ func TestAccGithubRepositoryTeamsDataSource(t *testing.T) { repository = github_repository.test.name permission = "push" } - `, randomID, randomID) + `, repoName, teamName) config2 := config + ` data "github_repository_teams" "test" { @@ -36,31 +38,25 @@ func TestAccGithubRepositoryTeamsDataSource(t *testing.T) { ` check := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("data.github_repository_teams.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_repository_teams.test", "name", repoName), resource.TestCheckResourceAttr("data.github_repository_teams.test", "teams.#", "1"), - resource.TestCheckResourceAttr("data.github_repository_teams.test", "teams.0.slug", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_repository_teams.test", "teams.0.slug", teamName), 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..7eb4c126b8 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,50 +9,88 @@ 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, + }, + }, }) }) t.Run("queries a repository with pages configured", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ds-pages-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" auto_init = true pages { source { @@ -65,7 +102,7 @@ func TestAccGithubRepositoryDataSource(t *testing.T) { data "github_repository" "test" { name = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -74,109 +111,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("%srepo-ds-defaults-%s", testResourcePrefix, 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,48 +174,65 @@ 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, + }, + }, }) }) t.Run("queries a repository that was generated from a template", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ds-template-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" template { - owner = "template-repository" - repository = "template-repository" + owner = "%s" + repository = "%s" } } data "github_repository" "test" { name = github_repository.test.name } - `, randomID) + `, repoName, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -239,44 +245,31 @@ 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 no primary_language", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ds-nolang-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" } data "github_repository" "test" { name = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -285,95 +278,66 @@ 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) + repoName := fmt.Sprintf("%srepo-ds-license-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" auto_init = true } resource "github_repository_file" "test" { @@ -394,7 +358,7 @@ EOT data "github_repository" "test" { name = github_repository_file.test.repository } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -403,29 +367,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..da1dd83277 100644 --- a/github/data_source_github_repository_webhooks_test.go +++ b/github/data_source_github_repository_webhooks_test.go @@ -10,69 +10,49 @@ import ( func TestAccGithubRepositoryWebhooksDataSource(t *testing.T) { t.Run("manages repository webhooks", func(t *testing.T) { - repoName := fmt.Sprintf("tf-acc-test-webhooks-%s", acctest.RandString(5)) + repoName := fmt.Sprintf("%srepo-webhooks-%s", testResourcePrefix, 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..030d2d7865 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" @@ -12,18 +11,19 @@ import ( func TestAccGithubRestApiDataSource(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-rest-api-%s", testResourcePrefix, randomID) t.Run("queries an existing branch without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_rest_api" "test" { endpoint = "repos/${github_repository.test.full_name}/git/refs/heads/${github_repository.test.default_branch}" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( @@ -36,85 +36,57 @@ 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("queries a collection without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_rest_api" "test" { endpoint = "repos/${github_repository.test.full_name}/git/refs/heads/" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( 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) + }, }) }) t.Run("queries an invalid branch without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } data "github_rest_api" "test" { endpoint = "repos/${github_repository.test.full_name}/git/refs/heads/xxxxxx" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( @@ -127,64 +99,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..dbc595f8f3 100644 --- a/github/data_source_github_team_test.go +++ b/github/data_source_github_team_test.go @@ -10,90 +10,64 @@ 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_team" "test" { slug = github_team.test.slug } - `, randomID) + `, teamName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_team.test", "name"), 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_team" "test" { slug = github_team.test.slug membership_type = "immediate" } - `, randomID) + `, teamName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_team.test", "name"), - resource.TestCheckResourceAttr("data.github_team.test", "name", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("data.github_team.test", "name", teamName), ) - testCase := 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,43 +78,31 @@ 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_team" "test" { slug = github_team.test.slug summary_only = true } - `, randomID) + `, teamName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_team.test", "name"), @@ -149,89 +111,120 @@ 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_team" "test" { slug = github_team.test.slug results_per_page = 20 } - `, randomID) + `, teamName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_team.test", "name"), 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) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` + 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_team" "test" { + name = "%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" + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + data "github_team" "test" { + slug = github_team.test.slug + + depends_on = [github_repository.test, github_team.test, github_team_repository.test] + } + `, repoName, teamName) + + 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository" "test" { - name = "tf-acc-test" + name = "%s" } resource "github_team_repository" "test" { team_id = github_team.test.id repository = github_repository.test.name permission = "admin" } - `, randomID) + `, teamName, repoName) config2 := config + ` data "github_team" "test" { @@ -241,39 +234,26 @@ func TestAccGithubTeamDataSource(t *testing.T) { check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("data.github_team.test", "name"), - resource.TestCheckResourceAttr("github_repository.test", "name", "tf-acc-test"), + resource.TestCheckResourceAttr("github_repository.test", "name", repoName), 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..394c079fb6 100644 --- a/github/data_source_github_tree_test.go +++ b/github/data_source_github_tree_test.go @@ -9,13 +9,13 @@ 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) + repoName := fmt.Sprintf("%srepo-tree-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "this" { auto_init = true - name = "tf-acc-test-%s" + name = "%s" } data "github_branch" "this" { @@ -28,7 +28,7 @@ func TestAccGithubTreeDataSource(t *testing.T) { repository = github_repository.this.name tree_sha = data.github_branch.this.sha } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -44,29 +44,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 a10d84c027..d96b919522 100644 --- a/github/provider.go +++ b/github/provider.go @@ -353,7 +353,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) } @@ -510,3 +510,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 3b4e53c328..5a7915cab7 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 47d7c43b17..0000000000 --- a/github/provider_utils.go +++ /dev/null @@ -1,145 +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, isGHES, err := getBaseURL(os.Getenv("GITHUB_BASE_URL")) - if err != nil { - return err - } - - 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, - IsGHES: isGHES, - } - - 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 b95fd2bf00..d480097c87 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..3164547ae4 100644 --- a/github/resource_github_actions_environment_secret_test.go +++ b/github/resource_github_actions_environment_secret_test.go @@ -12,15 +12,15 @@ 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) + repoName := fmt.Sprintf("%srepo-act-env-secret-%s", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -41,7 +41,7 @@ func TestAccGithubActionsEnvironmentSecret(t *testing.T) { secret_name = "test_encrypted_secret_name" encrypted_value = "%s" } - `, randomID, secretValue, secretValue) + `, repoName, secretValue, secretValue) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -78,44 +78,32 @@ 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) + repoName := fmt.Sprintf("%srepo-act-env-secret-%s", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -136,37 +124,24 @@ func TestAccGithubActionsEnvironmentSecret(t *testing.T) { secret_name = "test_encrypted_secret_name" encrypted_value = "%s" } - `, 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, - }, + `, repoName, secretValue, secretValue) + + 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) + }, }) }) } func TestAccGithubActionsEnvironmentSecretIgnoreChanges(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-env-secret-ic-%s", testResourcePrefix, randomID) t.Run("creates environment secrets using lifecycle ignore_changes", func(t *testing.T) { secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) @@ -174,7 +149,7 @@ func TestAccGithubActionsEnvironmentSecretIgnoreChanges(t *testing.T) { configFmtStr := ` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" # TODO: provider appears to have issues destroying repositories while running the tests. # @@ -250,49 +225,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, repoName, secretValue, secretValue), + Check: checks["before"], + }, + { + Config: fmt.Sprintf(configFmtStr, repoName, 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, repoName, 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..d448c15133 100644 --- a/github/resource_github_actions_environment_variable_test.go +++ b/github/resource_github_actions_environment_variable_test.go @@ -14,15 +14,15 @@ 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) + repoName := fmt.Sprintf("%srepo-act-env-var-%s", testResourcePrefix, randomID) value := "my_variable_value" updatedValue := "my_updated_variable_value" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -36,7 +36,7 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { variable_name = "test_variable" value = "%s" } - `, randomID, value) + `, repoName, value) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -65,42 +65,30 @@ 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) + repoName := fmt.Sprintf("%srepo-act-env-var-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -114,42 +102,30 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { variable_name = "test_variable" value = "my_variable_value" } - `, randomID) + `, repoName) - 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) + repoName := fmt.Sprintf("%srepo-act-env-var-%s", testResourcePrefix, randomID) value := "my_variable_value" envName := "environment / test" varName := "test_variable" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_environment" "test" { @@ -163,43 +139,29 @@ func TestAccGithubActionsEnvironmentVariable(t *testing.T) { variable_name = "%s" value = "%s" } - `, randomID, envName, varName, value) + `, 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{ - { - 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(`%s:%s:%s`, repoName, envName, varName), + ImportState: true, + ImportStateVerify: true, + }, + }, }) }) } func TestAccGithubActionsEnvironmentVariable_alreadyExists(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) + repoName := fmt.Sprintf("%srepo-act-env-var-exist-%s", testResourcePrefix, randomID) envName := "environment / test" varName := "test_variable" value := "my_variable_value" @@ -223,16 +185,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 +202,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..4fa46ecba2 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) + }, }) }) @@ -53,10 +47,11 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { githubOwnedAllowed := true verifiedAllowed := true randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-org-perm-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -73,7 +68,7 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { repository_ids = [github_repository.test.repo_id] } } - `, randomID, allowedActions, enabledRepositories, githubOwnedAllowed, verifiedAllowed) + `, repoName, allowedActions, enabledRepositories, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -90,26 +85,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 +133,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 +169,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) + }, }) }) @@ -211,16 +188,18 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { verifiedAllowed := true randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) randomID2 := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-org-perm-%s", testResourcePrefix, randomID) + repoName2 := fmt.Sprintf("%srepo-act-org-perm-%s", testResourcePrefix, randomID2) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } resource "github_repository" "test2" { - name = "tf-acc-test-topic-%[2]s" + name = "%[2]s" description = "Terraform acceptance tests %[2]s" topics = ["terraform", "testing"] } @@ -232,7 +211,7 @@ func TestAccGithubActionsOrganizationPermissions(t *testing.T) { repository_ids = [github_repository.test.repo_id, github_repository.test2.repo_id] } } - `, randomID, randomID2, allowedActions, enabledRepositories, githubOwnedAllowed, verifiedAllowed) + `, repoName, repoName2, allowedActions, enabledRepositories, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -246,21 +225,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_repositories_test.go b/github/resource_github_actions_organization_secret_repositories_test.go index ab721a1abc..dd37037d5d 100644 --- a/github/resource_github_actions_organization_secret_repositories_test.go +++ b/github/resource_github_actions_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,24 +9,24 @@ import ( ) func TestAccGithubActionsOrganizationSecretRepositories(t *testing.T) { - const ORG_SECRET_NAME = "ORG_SECRET_NAME" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - secret_name, exists := os.LookupEnv(ORG_SECRET_NAME) + repoName1 := fmt.Sprintf("%srepo-act-org-secret-%s-1", testResourcePrefix, randomID) + repoName2 := fmt.Sprintf("%srepo-act-org-secret-%s-2", testResourcePrefix, randomID) 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) + if len(testAccConf.testOrgSecretName) == 0 { + t.Skipf("'GH_TEST_ORG_SECRET_NAME' environment variable is missing") } config := fmt.Sprintf(` resource "github_repository" "test_repo_1" { - name = "tf-acc-test-%s-1" + name = "%s" visibility = "internal" vulnerability_alerts = "true" } resource "github_repository" "test_repo_2" { - name = "tf-acc-test-%s-2" + name = "%s" visibility = "internal" vulnerability_alerts = "true" } @@ -39,7 +38,7 @@ func TestAccGithubActionsOrganizationSecretRepositories(t *testing.T) { github_repository.test_repo_2.repo_id ] } - `, randomID, randomID, secret_name) + `, repoName1, repoName2, testAccConf.testOrgSecretName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -50,29 +49,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..c8e1533e8c 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,18 +9,17 @@ 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) + repoName := fmt.Sprintf("%srepo-act-org-secret-%s", testResourcePrefix, randomID) + secretName := testAccConf.testOrgSecretName + if len(secretName) == 0 { + t.Skip("test organization secret name is not set") } config := fmt.Sprintf(` resource "github_repository" "test_repo_1" { - name = "tf-acc-test-%s-1" + name = "%s" visibility = "internal" vulnerability_alerts = "true" } @@ -30,7 +28,7 @@ func TestAccGithubActionsOrganizationSecretRepository(t *testing.T) { secret_name = "%s" repository_id = github_repository.test_repo_1.repo_id } - `, randomID, secret_name) + `, repoName, secretName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -41,29 +39,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..52ac31fb21 100644 --- a/github/resource_github_actions_organization_variable_test.go +++ b/github/resource_github_actions_organization_variable_test.go @@ -53,45 +53,32 @@ 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"], + }, + }, }) }) t.Run("creates an organization variable scoped to a repo without error", func(t *testing.T) { value := "my_variable_value" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-org-var-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_organization_variable" "variable" { @@ -100,7 +87,7 @@ func TestAccGithubActionsOrganizationVariable(t *testing.T) { visibility = "selected" selected_repository_ids = [github_repository.test.repo_id] } - `, randomID, value) + `, repoName, value) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -125,29 +112,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 +133,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 +157,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..2661cc2dba 100644 --- a/github/resource_github_actions_repository_access_level_test.go +++ b/github/resource_github_actions_repository_access_level_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubActionsRepositoryAccessLevel(t *testing.T) { t.Run("test setting of user action access level", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-access-%s", testResourcePrefix, randomID) accessLevel := "user" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] visibility = "private" @@ -24,7 +25,7 @@ func TestAccGithubActionsRepositoryAccessLevel(t *testing.T) { access_level = "%s" repository = github_repository.test.name } - `, randomID, accessLevel) + `, repoName, accessLevel) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -32,38 +33,25 @@ 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") + }, }) }) t.Run("test setting of organization action access level", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-access-%s", testResourcePrefix, randomID) accessLevel := "organization" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] visibility = "private" @@ -73,7 +61,7 @@ func TestAccGithubActionsRepositoryAccessLevel(t *testing.T) { access_level = "%s" repository = github_repository.test.name } - `, randomID, accessLevel) + `, repoName, accessLevel) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -81,29 +69,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..ed29828432 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,12 +9,12 @@ 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) + repoName := fmt.Sprintf("%srepo-act-oidc-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } @@ -22,7 +22,7 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test repository = github_repository.test.name use_default = false include_claim_keys = ["repo", "context", "job_workflow_ref"] - }`, randomID) + }`, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -45,33 +45,24 @@ 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) + repoName := fmt.Sprintf("%srepo-act-oidc-%s", testResourcePrefix, randomID) configTemplate := ` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } @@ -86,7 +77,7 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test resetToDefaultConfigTemplate := ` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } @@ -97,11 +88,11 @@ func TestAccGithubActionsRepositoryOIDCSubjectClaimCustomizationTemplate(t *test ` configs := map[string]string{ - "before": fmt.Sprintf(configTemplate, randomID, false, claims), + "before": fmt.Sprintf(configTemplate, repoName, false, claims), - "after": fmt.Sprintf(configTemplate, randomID, false, updatedClaims), + "after": fmt.Sprintf(configTemplate, repoName, false, updatedClaims), - "reset_to_default": fmt.Sprintf(resetToDefaultConfigTemplate, randomID), + "reset_to_default": fmt.Sprintf(resetToDefaultConfigTemplate, repoName), } checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -160,51 +151,39 @@ 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) + repoName := fmt.Sprintf("%srepo-act-oidc-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" } resource "github_actions_repository_oidc_subject_claim_customization_template" "test" { repository = github_repository.test.name use_default = false include_claim_keys = ["repository_owner_id", "run_id", "workflow"] - }`, randomID) + }`, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -229,33 +208,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..a04f556aab 100644 --- a/github/resource_github_actions_repository_permissions_test.go +++ b/github/resource_github_actions_repository_permissions_test.go @@ -12,10 +12,11 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { t.Run("test setting of basic actions repository permissions", func(t *testing.T) { allowedActions := "local_only" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -24,7 +25,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { allowed_actions = "%s" repository = github_repository.test.name } - `, randomID, allowedActions) + `, repoName, allowedActions) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -32,29 +33,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) + }, }) }) @@ -63,10 +50,11 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { githubOwnedAllowed := true verifiedAllowed := true randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -80,7 +68,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { } repository = github_repository.test.name } - `, randomID, allowedActions, githubOwnedAllowed, verifiedAllowed) + `, repoName, allowedActions, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -91,34 +79,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, + }, + }, }) }) @@ -127,10 +101,11 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { githubOwnedAllowed := true verifiedAllowed := true randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -144,7 +119,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { } repository = github_repository.test.name } - `, randomID, allowedActions, githubOwnedAllowed, verifiedAllowed) + `, repoName, allowedActions, githubOwnedAllowed, verifiedAllowed) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -155,39 +130,26 @@ 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) + }, }) }) t.Run("test not setting of repository allowed actions without error", func(t *testing.T) { allowedActions := "selected" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -196,7 +158,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { allowed_actions = "%s" repository = github_repository.test.name } - `, randomID, allowedActions) + `, repoName, allowedActions) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -209,39 +171,26 @@ 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) + }, }) }) t.Run("test disabling actions on a repository", func(t *testing.T) { actionsEnabled := false randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -250,7 +199,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { enabled = %t repository = github_repository.test.name } - `, randomID, actionsEnabled) + `, repoName, actionsEnabled) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -258,35 +207,22 @@ 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) + }, }) }) // https://github.com/integrations/terraform-provider-github/issues/2182 t.Run("test load with disabled actions", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` locals { @@ -294,7 +230,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-actions-permissions-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -304,7 +240,7 @@ func TestAccGithubActionsRepositoryPermissions(t *testing.T) { enabled = local.actions_enabled allowed_actions = local.actions_enabled ? "all" : null } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -315,29 +251,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..094897739b 100644 --- a/github/resource_github_actions_runner_group_test.go +++ b/github/resource_github_actions_runner_group_test.go @@ -12,31 +12,19 @@ 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) + repoName := fmt.Sprintf("%srepo-act-runner-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" vulnerability_alerts = false 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,14 +35,14 @@ 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) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -62,7 +50,7 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { ), resource.TestCheckResourceAttr( "github_actions_runner_group.test", "name", - fmt.Sprintf(`tf-acc-test-%s`, randomID), + repoName, ), resource.TestCheckResourceAttr( "github_actions_runner_group.test", "visibility", @@ -83,7 +71,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,38 +85,24 @@ 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) + repoName := fmt.Sprintf("%srepo-act-runner-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_runner_group" "test" { @@ -136,7 +110,7 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { visibility = "selected" selected_repository_ids = [github_repository.test.repo_id] } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -144,7 +118,7 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { ), resource.TestCheckResourceAttr( "github_actions_runner_group.test", "name", - fmt.Sprintf(`tf-acc-test-%s`, randomID), + repoName, ), resource.TestCheckResourceAttr( "github_actions_runner_group.test", "visibility", @@ -159,139 +133,105 @@ 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) + repoName := fmt.Sprintf("%srepo-act-runner-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_runner_group" "test" { name = github_repository.test.name visibility = "all" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "name"), resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "visibility"), resource.TestCheckResourceAttr("github_actions_runner_group.test", "visibility", "all"), - resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", repoName), ) - testCase := 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" + // Based on GitHub UI there is no way to create a private runner group + t.Skip("This is not supported") + + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-runner-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_runner_group" "test" { name = github_repository.test.name visibility = "private" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "name"), - resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", repoName), 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) + repoName := fmt.Sprintf("%srepo-act-runner-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_runner_group" "test" { @@ -299,11 +239,11 @@ func TestAccGithubActionsRunnerGroup(t *testing.T) { visibility = "selected" selected_repository_ids = [github_repository.test.repo_id] } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "name"), - resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_actions_runner_group.test", "name", repoName), resource.TestCheckResourceAttrSet("github_actions_runner_group.test", "visibility"), resource.TestCheckResourceAttr("github_actions_runner_group.test", "visibility", "selected"), resource.TestCheckResourceAttr( @@ -312,30 +252,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..3ea8ef697f 100644 --- a/github/resource_github_actions_secret_test.go +++ b/github/resource_github_actions_secret_test.go @@ -12,20 +12,19 @@ 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) + repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_actions_public_key" "test_pk" { repository = github_repository.test.name } - - `, randomID) + `, repoName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -36,39 +35,27 @@ 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) + repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_secret" "plaintext_secret" { @@ -82,7 +69,7 @@ func TestAccGithubActionsSecret(t *testing.T) { secret_name = "test_encrypted_secret" encrypted_value = "%s" } - `, randomID, secretValue, secretValue) + `, repoName, secretValue, secretValue) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -119,41 +106,28 @@ 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) { - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID) + updatedRepoName := fmt.Sprintf("%srepo-act-secret-%s-upd", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) config := fmt.Sprintf(` @@ -217,42 +191,30 @@ 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) + repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_secret" "plaintext_secret" { @@ -264,40 +226,27 @@ func TestAccGithubActionsSecret(t *testing.T) { repository = github_repository.test.name secret_name = "test_encrypted_secret" } - `, 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, - }, + `, repoName) + + 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("respects destroy_on_drift setting", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-act-secret-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_secret" "with_drift_true" { @@ -320,44 +269,30 @@ func TestAccGithubActionsSecret(t *testing.T) { plaintext_value = "initial_value" # destroy_on_drift defaults to true } - `, 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"), - ), - }, + `, repoName) + + 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..f08ed44e6d 100644 --- a/github/resource_github_actions_variable_test.go +++ b/github/resource_github_actions_variable_test.go @@ -11,15 +11,15 @@ 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) + repoName := fmt.Sprintf("%srepo-act-var-%s", testResourcePrefix, randomID) value := "my_variable_value" updatedValue := "my_updated_variable_value" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_variable" "variable" { @@ -27,7 +27,7 @@ func TestAccGithubActionsVariable(t *testing.T) { variable_name = "test_variable" value = "%s" } - `, randomID, value) + `, repoName, value) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -56,42 +56,30 @@ 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) + repoName := fmt.Sprintf("%srepo-act-var-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_variable" "variable" { @@ -99,41 +87,29 @@ func TestAccGithubActionsVariable(t *testing.T) { variable_name = "test_variable" value = "my_variable_value" } - `, 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, - }, + `, repoName) + + 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) + repoName := fmt.Sprintf("%srepo-act-var-%s", testResourcePrefix, randomID) varName := "test_variable" value := "variable_value" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_actions_variable" "variable" { @@ -141,36 +117,22 @@ func TestAccGithubActionsVariable(t *testing.T) { variable_name = "%s" value = "%s" } - `, 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, - }, + `, repoName, varName, value) + + 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(`%s:%s`, repoName, 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..8c07b8f13a 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("%srepo-app-install-0-%s", testResourcePrefix, randomID) + repoName1 := fmt.Sprintf("%srepo-app-install-1-%s", testResourcePrefix, 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" { - name = "tf-acc-test-%s" + resource "github_repository" "test_1" { + name = "%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..70954a02e4 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,29 +9,29 @@ 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) + repoName := fmt.Sprintf("%srepo-app-install-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } 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) + `, repoName, testAccConf.testOrgAppInstallationId) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -43,29 +42,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..ba9e1550a8 100644 --- a/github/resource_github_branch_default_test.go +++ b/github/resource_github_branch_default_test.go @@ -9,13 +9,13 @@ 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) + repoName := fmt.Sprintf("%srepo-branch-def-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -23,7 +23,7 @@ func TestAccGithubBranchDefault(t *testing.T) { repository = github_repository.test.name branch = "main" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -32,40 +32,28 @@ func TestAccGithubBranchDefault(t *testing.T) { ), resource.TestCheckResourceAttr( "github_branch_default.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), ) - testCase := 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) + repoName := fmt.Sprintf("%srepo-branch-def-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -79,7 +67,7 @@ func TestAccGithubBranchDefault(t *testing.T) { branch = github_branch.test.branch } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -88,37 +76,32 @@ 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) + repoName := fmt.Sprintf("%srepo-branch-def-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -127,7 +110,7 @@ func TestAccGithubBranchDefault(t *testing.T) { branch = "main" rename = true } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -136,40 +119,28 @@ func TestAccGithubBranchDefault(t *testing.T) { ), resource.TestCheckResourceAttr( "github_branch_default.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), ) - testCase := 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) + repoName := fmt.Sprintf("%srepo-branch-def-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -178,39 +149,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, - }, + `, repoName) + + 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..eadb1452b3 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,44 +536,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, - }, + 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 allow force push with a team as bypasser", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } resource "github_team" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_team_repository" "test" { @@ -718,7 +578,7 @@ func TestAccGithubBranchProtectionV4(t *testing.T) { ] } - `, randomID, randomID, testOrganization) + `, repoName, teamName, testAccConf.owner) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr( @@ -729,22 +589,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 +628,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 +657,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 +671,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 +712,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..7f7ff73e69 100644 --- a/github/resource_github_branch_protection_v3_test.go +++ b/github/resource_github_branch_protection_v3_test.go @@ -8,282 +8,490 @@ 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) { + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) + 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 = "%s" + auto_init = true + } - resource "github_branch_protection_v3" "test" { + resource "github_team" "test" { + name = "%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" { - `, randomID) + 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] + } + `, repoName, teamName) 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) { + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) + 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 = "%s" + auto_init = true + } - resource "github_branch_protection_v3" "test" { + resource "github_team" "test" { + name = "%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" - `, randomID) + required_pull_request_reviews { + bypass_pull_request_allowances { + teams = [github_team.test.slug] + } + } + + depends_on = [github_team_repository.test] + } + + `, repoName, teamName) 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) { + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-%s", testResourcePrefix, randomID) + t.Run("configures branch push restrictions", func(t *testing.T) { config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } + resource "github_team" "test" { + name = "%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) + `, repoName, teamName) 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 +572,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 +627,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 +675,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..ae13c32355 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,202 +9,120 @@ 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) + repoName := fmt.Sprintf("%srepo-branch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" - auto_init = true - } - - resource "github_branch" "test" { - repository = github_repository.test.id - 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 "github_repository" "test" { + name = "%[1]s" + auto_init = 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) + resource "github_branch" "test" { + repository = github_repository.test.name + branch = "test" + } + `, repoName) + + 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("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) + repoName := fmt.Sprintf("%srepo-branch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - 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" - } - `, 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 "github_repository" "test" { + name = "%[1]s" + auto_init = true + gitignore_template = "Python" } - t.Run("with an anonymous 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) + resource "github_branch" "test" { + repository = github_repository.test.id + branch = "main" + } + `, repoName) + + 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"), + ), + }, + { + 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) + repoName := fmt.Sprintf("%srepo-branch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - 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" "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 "github_repository" "test" { + name = "%[1]s" + auto_init = 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) - }) + resource "github_branch" "source" { + repository = github_repository.test.id + branch = "source" + } - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + resource "github_branch" "test" { + repository = github_repository.test.id + source_branch = github_branch.source.branch + branch = "test" + } + `, repoName) + + 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("renames a branch without replacement", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-branch-%s", testResourcePrefix, randomID) initialConfig := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } @@ -213,11 +130,11 @@ func TestAccGithubBranch(t *testing.T) { repository = github_repository.test.id branch = "initial" } - `, randomID) + `, repoName) renamedConfig := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%[1]s" auto_init = true } @@ -225,38 +142,24 @@ func TestAccGithubBranch(t *testing.T) { repository = github_repository.test.id branch = "renamed" } - `, 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", - ), + `, repoName) + + 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..07d3ee9cb9 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,49 @@ 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) + repoName1 := fmt.Sprintf("%srepo-cs-org-secret-1-%s", testResourcePrefix, randomID) + repoName2 := fmt.Sprintf("%srepo-cs-org-secret-2-%s", testResourcePrefix, randomID) 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" + name = "%s" + visibility = "private" } resource "github_repository" "test_repo_2" { - name = "tf-acc-test-%s-2" - visibility = "internal" + name = "%s" + 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, - }, + `, repoName1, repoName2) + + 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..55bf8e9665 100644 --- a/github/resource_github_codespaces_secret_test.go +++ b/github/resource_github_codespaces_secret_test.go @@ -12,20 +12,20 @@ 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) + repoName := fmt.Sprintf("%srepo-codespaces-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_codespaces_public_key" "test_pk" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -36,39 +36,27 @@ 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) + repoName := fmt.Sprintf("%srepo-codespaces-%s", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_codespaces_secret" "plaintext_secret" { @@ -82,7 +70,7 @@ func TestAccGithubCodespacesSecret(t *testing.T) { secret_name = "test_encrypted_secret" encrypted_value = "%s" } - `, randomID, secretValue, secretValue) + `, repoName, secretValue, secretValue) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -119,41 +107,28 @@ 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) { - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-codespaces-%s", testResourcePrefix, randomID) + updatedRepoName := fmt.Sprintf("%s-updated", repoName) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) config := fmt.Sprintf(` @@ -215,42 +190,30 @@ 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) + repoName := fmt.Sprintf("%srepo-codespaces-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_codespaces_secret" "plaintext_secret" { @@ -262,31 +225,17 @@ func TestAccGithubCodespacesSecret(t *testing.T) { repository = github_repository.test.name secret_name = "test_encrypted_secret" } - `, 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, - }, + `, repoName) + + 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..4ff6354b42 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,51 @@ 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) + repoName1 := fmt.Sprintf("%srepo-depbot-org-secret-1-%s", testResourcePrefix, randomID) + repoName2 := fmt.Sprintf("%srepo-depbot-org-secret-2-%s", testResourcePrefix, randomID) 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 = "%s" + 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 = "%s" + 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 + ] + } + `, repoName1, repoName2) + + 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..62787c8d35 100644 --- a/github/resource_github_dependabot_secret_test.go +++ b/github/resource_github_dependabot_secret_test.go @@ -12,20 +12,20 @@ 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) + repoName := fmt.Sprintf("%srepo-dependabot-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } data "github_dependabot_public_key" "test_pk" { repository = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet( @@ -36,39 +36,27 @@ 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) + repoName := fmt.Sprintf("%srepo-dependabot-%s", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) updatedSecretValue := base64.StdEncoding.EncodeToString([]byte("updated_super_secret_value")) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_dependabot_secret" "plaintext_secret" { @@ -82,7 +70,7 @@ func TestAccGithubDependabotSecret(t *testing.T) { secret_name = "test_encrypted_secret" encrypted_value = "%s" } - `, randomID, secretValue, secretValue) + `, repoName, secretValue, secretValue) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -119,41 +107,28 @@ 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) { - repoName := fmt.Sprintf("tf-acc-test-%s", randomID) - updatedRepoName := fmt.Sprintf("tf-acc-test-%s-updated", randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-dependabot-%s", testResourcePrefix, randomID) + updatedRepoName := fmt.Sprintf("%srepo-dependabot-%s-upd", testResourcePrefix, randomID) secretValue := base64.StdEncoding.EncodeToString([]byte("super_secret_value")) config := fmt.Sprintf(` @@ -217,42 +192,30 @@ 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) + repoName := fmt.Sprintf("%srepo-dependabot-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_dependabot_secret" "plaintext_secret" { @@ -264,31 +227,17 @@ func TestAccGithubDependabotSecret(t *testing.T) { repository = github_repository.test.name secret_name = "test_encrypted_secret" } - `, 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, - }, + `, repoName) + + 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..784885bf48 100644 --- a/github/resource_github_etag_acc_test.go +++ b/github/resource_github_etag_acc_test.go @@ -11,7 +11,7 @@ import ( // TestAccGithubRepositoryEtagPresent tests that etag field is populated. func TestAccGithubRepositoryEtagPresent(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - repoName := fmt.Sprintf("tf-acc-test-etag-%s", randomID) + repoName := fmt.Sprintf("%srepo-etag-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -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{ { @@ -38,7 +38,7 @@ func TestAccGithubRepositoryEtagPresent(t *testing.T) { // TestAccGithubRepositoryEtagNoDiff tests that re-running the same config shows no changes. func TestAccGithubRepositoryEtagNoDiff(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - repoName := fmt.Sprintf("tf-acc-test-etag-nodiff-%s", randomID) + repoName := fmt.Sprintf("%srepo-etag-nodiff-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -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..b56bfbfe54 100644 --- a/github/resource_github_issue_label_test.go +++ b/github/resource_github_issue_label_test.go @@ -10,16 +10,16 @@ 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) + repoName := fmt.Sprintf("%srepo-issue-label-%s", testResourcePrefix, randomID) description := "label_description" updatedDescription := "updated_label_description" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -29,7 +29,7 @@ func TestAccGithubIssueLabel(t *testing.T) { color = "000000" description = "%s" } - `, randomID, description) + `, repoName, description) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -46,42 +46,31 @@ 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) + repoName := fmt.Sprintf("%srepo-issue-label-arch-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-archive-%s" + name = "%s" auto_init = true } @@ -91,57 +80,47 @@ func TestAccGithubIssueLabel(t *testing.T) { color = "ff0000" description = "Test label for archived repo" } - `, randomID) + `, repoName) archivedConfig := strings.Replace(config, `auto_init = true`, `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" + name = "%s" auto_init = true archived = true } - `, randomID), - }, + `, 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_labels_test.go b/github/resource_github_issue_labels_test.go index b45f8f2b04..d512288081 100644 --- a/github/resource_github_issue_labels_test.go +++ b/github/resource_github_issue_labels_test.go @@ -1,120 +1,81 @@ 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" ) 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)) + repoName := fmt.Sprintf("%srepo-issue-labels-%s", testResourcePrefix, 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,20 +113,11 @@ 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) t.Run("can delete labels from archived repositories without error", func(t *testing.T) { - repoName := fmt.Sprintf("tf-acc-test-labels-archive-%s", randomID) + repoName := fmt.Sprintf("%srepo-labels-arch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { @@ -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..3741dd15a6 100644 --- a/github/resource_github_issue_test.go +++ b/github/resource_github_issue_test.go @@ -11,9 +11,9 @@ 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) + repoName := fmt.Sprintf("%srepo-issue-%s", testResourcePrefix, randomID) title := "issue_title" body := "issue_body" labels := "\"bug\", \"enhancement\"" @@ -23,7 +23,7 @@ func TestAccGithubIssue(t *testing.T) { issueHCL := ` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true has_issues = true } @@ -46,7 +46,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, repoName, title, body, labels, testAccConf.username) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -93,40 +93,28 @@ 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, repoName, 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) + repoName := fmt.Sprintf("%srepo-issue-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" has_issues = true } @@ -134,41 +122,27 @@ func TestAccGithubIssue(t *testing.T) { repository = github_repository.test.name title = github_repository.test.name } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_issue.test", "title"), - resource.TestCheckResourceAttr("github_issue.test", "title", fmt.Sprintf(`tf-acc-test-%s`, randomID)), + resource.TestCheckResourceAttr("github_issue.test", "title", repoName), ) - testCase := 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_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..43d423dfbb 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) { - teamSlug := fmt.Sprintf("tf-acc-test-team-repo-%s", randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamSlug := fmt.Sprintf("%steam-role-assign-%s", testResourcePrefix, 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) { - teamSlug := fmt.Sprintf("tf-acc-test-team-repo-%s", randomID) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamSlug := fmt.Sprintf("%steam-role-assign-%s", testResourcePrefix, 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..e38f7ab414 100644 --- a/github/resource_github_organization_role_team_test.go +++ b/github/resource_github_organization_role_team_test.go @@ -12,7 +12,7 @@ import ( func TestAccGithubOrganizationRoleTeam(t *testing.T) { t.Run("adds team to an organization org role", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - teamName := fmt.Sprintf("tf-acc-team-%s", randomID) + teamName := fmt.Sprintf("%steam-org-role-%s", testResourcePrefix, randomID) roleId := 8134 config := fmt.Sprintf(` resource "github_team" "test" { @@ -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..6a12c2bac7 100644 --- a/github/resource_github_organization_role_user_test.go +++ b/github/resource_github_organization_role_user_test.go @@ -2,7 +2,6 @@ package github import ( "fmt" - "os" "strconv" "testing" @@ -11,28 +10,23 @@ import ( func TestAccGithubOrganizationRoleUser(t *testing.T) { t.Run("adds user to an organization org role", func(t *testing.T) { - login := os.Getenv("GITHUB_IN_ORG_USER") - if len(login) == 0 { - t.Skip("set inOrgUser to unskip this test run") - } - roleId := 8134 config := fmt.Sprintf(` resource "github_organization_role_user" "test" { role_id = %d login = "%s" } - `, roleId, login) + `, roleId, testAccConf.testOrgUser) resource.Test(t, resource.TestCase{ - PreCheck: func() { skipUnlessMode(t, organization) }, + PreCheck: func() { skipUnlessHasOrgs(t) }, Providers: testAccProviders, Steps: []resource.TestStep{ { Config: config, Check: resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr("github_organization_role_user.test", "role_id", strconv.Itoa(roleId)), - resource.TestCheckResourceAttr("github_organization_role_user.test", "login", login), + resource.TestCheckResourceAttr("github_organization_role_user.test", "login", testAccConf.testOrgUser), ), }, }, 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..e8611c133b 100644 --- a/github/resource_github_organization_security_manager_test.go +++ b/github/resource_github_organization_security_manager_test.go @@ -9,164 +9,80 @@ 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) + teamName := fmt.Sprintf("%steam-sec-mgr-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-%s" + name = "%s" } resource "github_organization_security_manager" "test" { team_slug = github_team.test.slug } - `, 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)), - ), - }, + `, teamName) + + 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", teamName), + ), }, - }) - } - - t.Run("with an anonymous 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) + teamName := fmt.Sprintf("%steam-sec-mgr-%s", testResourcePrefix, randomID) + teamNameUpdated := fmt.Sprintf("%s-updated", teamName) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-%s" + name = "%s" } resource "github_organization_security_manager" "test" { team_slug = github_team.test.slug } - `, randomID) + `, teamName) configUpdated := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-updated-%s" + name = "%s" } resource "github_organization_security_manager" "test" { team_slug = github_team.test.slug } - `, 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)), - ), - }, + `, teamNameUpdated) + + 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", teamName), + ), }, - }) - } - - t.Run("with an anonymous 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) { - config := fmt.Sprintf(` - resource "github_team" "test" { - name = "tf-acc-%s" - } - - resource "github_organization_security_manager" "test" { - team_slug = github_team.test.slug - } - `, randomID) - - configUpdated := fmt.Sprintf(` - resource "github_team" "test" { - name = "tf-acc-updated-%s" - } - - resource "github_organization_security_manager" "test" { - team_slug = github_team.test.slug - } - `, 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)), - ), - }, + { + 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", teamNameUpdated), + ), }, - }) - } - - t.Run("with an anonymous 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_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..77c44b9a09 100644 --- a/github/resource_github_organization_webhook_test.go +++ b/github/resource_github_organization_webhook_test.go @@ -10,13 +10,13 @@ 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) + repoName := fmt.Sprintf("%srepo-org-webhook-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -30,7 +30,7 @@ func TestAccGithubOrganizationWebhook(t *testing.T) { events = ["pull_request"] } - `, randomID) + `, repoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -47,43 +47,31 @@ 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) + repoName := fmt.Sprintf("%srepo-org-webhook-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -97,7 +85,7 @@ func TestAccGithubOrganizationWebhook(t *testing.T) { events = ["issues"] } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -106,34 +94,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..4364db8715 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,37 +40,25 @@ 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) + repoName := fmt.Sprintf("%srepo-project-card-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" has_projects = true has_issues = true } @@ -97,9 +84,10 @@ 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) + `, repoName) check := resource.ComposeTestCheckFunc( func(state *terraform.State) error { @@ -116,29 +104,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..4b2694272b 100644 --- a/github/resource_github_release_test.go +++ b/github/resource_github_release_test.go @@ -14,11 +14,12 @@ import ( func TestAccGithubReleaseResource(t *testing.T) { t.Run("create a release with defaults", func(t *testing.T) { randomRepoPart := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-release-%s", testResourcePrefix, randomRepoPart) randomVersion := fmt.Sprintf("v1.0.%d", acctest.RandIntRange(0, 9999)) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -26,7 +27,7 @@ func TestAccGithubReleaseResource(t *testing.T) { repository = github_repository.test.name tag_name = "%s" } - `, randomRepoPart, randomVersion) + `, repoName, randomVersion) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -55,47 +56,34 @@ 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"), + }, + }, }) }) t.Run("create a release on branch", func(t *testing.T) { randomRepoPart := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-release-%s", testResourcePrefix, randomRepoPart) randomVersion := fmt.Sprintf("v1.0.%d", acctest.RandIntRange(0, 9999)) testBranchName := "test" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -112,7 +100,7 @@ func TestAccGithubReleaseResource(t *testing.T) { draft = false prerelease = false } - `, randomRepoPart, testBranchName, randomVersion) + `, repoName, testBranchName, randomVersion) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -141,36 +129,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.go b/github/resource_github_repository.go index 2be5f8717f..4bd466b3ef 100644 --- a/github/resource_github_repository.go +++ b/github/resource_github_repository.go @@ -8,9 +8,12 @@ import ( "net/http" "regexp" "strings" + "time" "github.com/google/go-github/v67/github" + "github.com/hashicorp/terraform-plugin-log/tflog" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/customdiff" + "github.com/hashicorp/terraform-plugin-sdk/v2/helper/retry" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema" "github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation" ) @@ -752,6 +755,12 @@ func resourceGithubRepositoryCreate(d *schema.ResourceData, meta any) error { d.SetId(repo.GetName()) } + retryErr := waitForRepositoryToBeCreated(ctx, client, owner, repoName) + + if retryErr != nil { + return fmt.Errorf("error waiting for repository to be created: %w", retryErr) + } + topics := repoReq.Topics if len(topics) > 0 { _, _, err := client.Repositories.ReplaceAllTopics(ctx, owner, repoName, topics) @@ -1251,3 +1260,29 @@ func updateVulnerabilityAlerts(d *schema.ResourceData, client *github.Client, ct _, err := updateVulnerabilityAlerts(ctx, owner, repoName) return err } + +// The Repository Create API doesn't wait for the repository to be created, so we need to enable a retry mechanism to wait for it. +// Resolves https://github.com/integrations/terraform-provider-github/issues/2604 +func waitForRepositoryToBeCreated(ctx context.Context, client *github.Client, owner, repoName string) error { + timeout := 2 * time.Minute + return retry.RetryContext(ctx, timeout, func() *retry.RetryError { + tflog.Info(ctx, fmt.Sprintf("Waiting for repository to be created: %s/%s", owner, repoName)) + _, resp, err := client.Repositories.Get(ctx, owner, repoName) + if err != nil { + tflog.Debug(ctx, fmt.Sprintf("Error getting repository: %s", err)) + if resp.StatusCode == http.StatusForbidden { + return retry.NonRetryableError(fmt.Errorf("forbidden from accessing repository: %w", err)) + } + return retry.RetryableError(fmt.Errorf("expected repository to be created but was in state %s", resp.Status)) + + } + + if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusMovedPermanently { + return retry.RetryableError(fmt.Errorf("expected repository to be created but was in state %s", resp.Status)) + } + + tflog.Info(ctx, fmt.Sprintf("Repository created: %s/%s", owner, repoName)) + + return nil + }) +} diff --git a/github/resource_github_repository_autolink_reference_test.go b/github/resource_github_repository_autolink_reference_test.go index 0afa69392c..d057808cf9 100644 --- a/github/resource_github_repository_autolink_reference_test.go +++ b/github/resource_github_repository_autolink_reference_test.go @@ -10,12 +10,12 @@ 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) + repoName := fmt.Sprintf("%srepo-autolink-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%s" + name = "%s" description = "Test autolink creation" } @@ -48,7 +48,7 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { key_prefix = "TEST4-" target_url_template = "https://example.com:8443/TEST-" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( // autolink_default @@ -93,36 +93,24 @@ 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) + repoName := fmt.Sprintf("%srepo-autolink-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%s" + name = "%s" description = "Test autolink creation" } @@ -155,7 +143,7 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { key_prefix = "TEST4-" target_url_template = "https://example.com:8443/TEST-" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( // autolink_default @@ -200,64 +188,52 @@ 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("%s/", repoName), + }, + // autolink_alphanumeric + { + ResourceName: "github_repository_autolink_reference.autolink_alphanumeric", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("%s/", repoName), + }, + // autolink_numeric + { + ResourceName: "github_repository_autolink_reference.autolink_numeric", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("%s/", repoName), + }, + // autolink_with_port + { + ResourceName: "github_repository_autolink_reference.autolink_with_port", + ImportState: true, + ImportStateVerify: true, + ImportStateIdPrefix: fmt.Sprintf("%s/", repoName), + }, + }, }) }) t.Run("imports repository autolink reference by key prefix without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-autolink-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "oof" { - name = "oof-%s" + name = "%s" description = "Test autolink creation" } @@ -267,49 +243,37 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { key_prefix = "OOF-" target_url_template = "https://awesome.com/find/OOF-" } - `, 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`), - }, + `, repoName) + + 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("%s/OOF-", repoName), + }, + { + ResourceName: "github_repository_autolink_reference.autolink", + ImportState: true, + ImportStateId: fmt.Sprintf("%s/OCTOCAT-", repoName), + 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) + repoName := fmt.Sprintf("%srepo-autolink-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%s" + name = "%s" description = "Test autolink creation" } @@ -319,31 +283,17 @@ func TestAccGithubRepositoryAutolinkReference(t *testing.T) { key_prefix = "TEST1-" target_url_template = "https://example.com/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, - Destroy: true, - }, + `, repoName) + + 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..cce40b5dda 100644 --- a/github/resource_github_repository_collaborator_test.go +++ b/github/resource_github_repository_collaborator_test.go @@ -10,23 +10,25 @@ 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) + repoName := fmt.Sprintf("%srepo-collab-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } resource "github_repository_collaborator" "test_repo_collaborator" { repository = "${github_repository.test.name}" - username = "" + username = "%s" permission = "triage" } - `, randomID) + `, repoName, testAccConf.testExternalUser) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -35,51 +37,33 @@ 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) + repoName := fmt.Sprintf("%srepo-collab-%s", testResourcePrefix, randomID) configWithOwner := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } resource "github_repository_collaborator" "test_repo_collaborator_2" { repository = "%s/${github_repository.test.name}" - username = "" + username = "%s" permission = "triage" } - `, randomID, orgName) + `, repoName, testAccConf.owner, testAccConf.testExternalUser) checkWithOwner := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -88,29 +72,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) + }, }) }) } @@ -151,18 +121,19 @@ func TestParseRepoName(t *testing.T) { } 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") } + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-collab-arch-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-collab-archive-%s" + name = "%s" auto_init = true } @@ -171,11 +142,11 @@ func TestAccGithubRepositoryCollaboratorArchivedRepo(t *testing.T) { username = "%s" permission = "pull" } - `, randomID, testCollaborator) + `, repoName, testCollaborator) archivedConfig := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-collab-archive-%s" + name = "%s" auto_init = true archived = true } @@ -185,56 +156,46 @@ func TestAccGithubRepositoryCollaboratorArchivedRepo(t *testing.T) { username = "%s" permission = "pull" } - `, 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", - ), + `, repoName, testCollaborator) + + 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" + name = "%s" auto_init = true archived = true } - `, randomID), - }, + `, repoName), }, - }) - } - - 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 3e9e1f010c..debf8b737d 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,35 +12,22 @@ import ( ) func TestAccGithubRepositoryCollaborators(t *testing.T) { - inOrgUser := os.Getenv("GITHUB_IN_ORG_USER") - inOrgUser2 := os.Getenv("GITHUB_IN_ORG_USER2") - - baseURL, isGHES, err := getBaseURL(os.Getenv("GITHUB_BASE_URL")) - if err != nil { - t.Fatalf("failed to parse base URL: %s", err.Error()) + if len(testAccConf.testExternalUser) == 0 { + t.Skip("No external user provided") } - config := Config{BaseURL: baseURL, IsGHES: isGHES, 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) + repoName := fmt.Sprintf("%srepo-collabs-%s", testResourcePrefix, randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -57,9 +42,63 @@ func TestAccGithubRepositoryCollaborators(t *testing.T) { permission = "push" } } - `, repoName, inOrgUser) + `, repoName, testAccConf.testExternalUser) + + 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("%srepo-collabs-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-collabs-%s", testResourcePrefix, randomID) + collaboratorUser := testAccConf.testOrgUser - orgConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -77,139 +116,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, collaboratorUser) - 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 != collaboratorUser { + return fmt.Errorf("expected user.*.username to be set to %s, was %s", collaboratorUser, 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 1 collaborator (%s) for repo %s/%s , found %d", collaboratorUser, owner, repoName, len(users)) + } + perm := getPermission(users[0].GetRoleName()) + if perm != "admin" { + return fmt.Errorf("expected %s to have admin perms for repo %s/%s, found %s", collaboratorUser, 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) + repoName := fmt.Sprintf("%srepo-collabs-%s", testResourcePrefix, randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -224,9 +209,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 @@ -241,9 +226,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") + } + + ctx := t.Context() + conn := meta.v3client + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-collabs-%s", testResourcePrefix, randomID) + teamName1 := fmt.Sprintf("%steam-collabs-1-%s", testResourcePrefix, randomID) + teamName2 := fmt.Sprintf("%steam-collabs-2-%s", testResourcePrefix, randomID) - orgConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -278,9 +324,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 @@ -307,135 +353,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) + repoName := fmt.Sprintf("%srepo-collabs-%s", testResourcePrefix, randomID) - individualConfig := fmt.Sprintf(` + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -450,9 +440,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 @@ -460,7 +450,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("%srepo-collabs-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-collabs-%s", testResourcePrefix, randomID) + + config := fmt.Sprintf(` resource "github_repository" "test" { name = "%s" auto_init = true @@ -487,9 +516,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 @@ -501,180 +530,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..3121f52d00 100644 --- a/github/resource_github_repository_custom_property_test.go +++ b/github/resource_github_repository_custom_property_test.go @@ -9,196 +9,170 @@ 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) + repoName := fmt.Sprintf("%srepo-custom-prop-%s", testResourcePrefix, randomID) + 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-prop-%s", testResourcePrefix, randomID) + 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-prop-%s", testResourcePrefix, randomID) + 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" + name = "%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, repoName) 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) + repoName := fmt.Sprintf("%srepo-custom-prop-%s", testResourcePrefix, randomID) + 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" + name = "%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, repoName) 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 51% rename from github/resource_github_repository_automated_security_fixes_test.go rename to github/resource_github_repository_dependabot_security_updates_test.go index 04b6081255..6b42a602c7 100644 --- a/github/resource_github_repository_automated_security_fixes_test.go +++ b/github/resource_github_repository_dependabot_security_updates_test.go @@ -9,16 +9,16 @@ 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) + repoName := fmt.Sprintf("%srepo-depbot-updates-%s", testResourcePrefix, randomID) enabled := "enabled = false" updatedEnabled := "enabled = true" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" auto_init = true vulnerability_alerts = true @@ -29,7 +29,7 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { repository = github_repository.test.id %s } - `, randomID, enabled) + `, repoName, enabled) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -46,46 +46,34 @@ 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) + repoName := fmt.Sprintf("%srepo-depbot-updates-%s", testResourcePrefix, randomID) enabled := "enabled = true" updatedEnabled := "enabled = false" config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "private" auto_init = true vulnerability_alerts = true @@ -96,7 +84,7 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { repository = github_repository.test.id %s } - `, randomID, enabled) + `, repoName, enabled) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -113,42 +101,30 @@ 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) + repoName := fmt.Sprintf("%srepo-depbot-updates-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" vulnerability_alerts = true } @@ -156,7 +132,7 @@ func TestAccGithubAutomatedSecurityFixes(t *testing.T) { repository = github_repository.test.id enabled = false } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttrSet("github_repository_dependabot_security_updates.test", "repository"), @@ -164,34 +140,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..c38317b8bc 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("%srepo-deploy-key-%s", testResourcePrefix, 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,92 +162,87 @@ 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)), "\\", "/") + repoName := fmt.Sprintf("%srepo-deploy-key-arch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-deploy-key-archive-%s" + name = "%s" auto_init = true } 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) + `, repoName, keyPath) archivedConfig := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-deploy-key-archive-%s" + name = "%s" auto_init = true archived = true } 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", - ), + `, repoName, 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" + name = "%s" auto_init = true archived = true } - `, randomID), - }, + `, repoName), }, - }) - } - - 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..403911619d 100644 --- a/github/resource_github_repository_deployment_branch_policy_test.go +++ b/github/resource_github_repository_deployment_branch_policy_test.go @@ -9,13 +9,13 @@ 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) + repoName := fmt.Sprintf("%srepo-deploy-bp-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -27,7 +27,7 @@ func TestAccGithubRepositoryDeploymentBranchPolicy(t *testing.T) { custom_branch_policies = true } } - `, randomID) + `, repoName) config1 := ` resource "github_repository_deployment_branch_policy" "br" { @@ -60,33 +60,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 2318c10132..d3cc2a1592 100644 --- a/github/resource_github_repository_environment_deployment_policy_test.go +++ b/github/resource_github_repository_environment_deployment_policy_test.go @@ -11,9 +11,9 @@ import ( ) func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranch(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("creates a repository environment with branch-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` data "github_user" "current" { @@ -21,7 +21,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranch(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -44,12 +44,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranch(t *testing.T) { branch_pattern = "releases/*" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -64,37 +64,23 @@ 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) }, + 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) + }, }) }) } 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) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) var deploymentPolicyId string config1 := fmt.Sprintf(` @@ -104,7 +90,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -127,12 +113,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T branch_pattern = "main" } - `, randomID) + `, repoName) check1 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -155,7 +141,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -178,10 +164,10 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchUpdate(t *testing.T branch_pattern = "release/*" } - `, randomID) + `, repoName) check2 := resource.ComposeTestCheckFunc( - resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "repository", fmt.Sprintf("tf-acc-test-%s", randomID)), + resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "repository", repoName), resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "environment", "environment/test"), resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "branch_pattern", "release/*"), resource.TestCheckNoResourceAttr("github_repository_environment_deployment_policy.test", "tag_pattern"), @@ -191,41 +177,27 @@ 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) }, + Providers: testAccProviders, + 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) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` data "github_user" "current" { @@ -233,7 +205,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTag(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -256,12 +228,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTag(t *testing.T) { tag_pattern = "v*" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -276,37 +248,23 @@ 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) }, + 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) + }, }) }) } 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) var deploymentPolicyId string config1 := fmt.Sprintf(` @@ -316,7 +274,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -339,12 +297,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { tag_pattern = "v*" } - `, randomID) + `, repoName) check1 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -367,7 +325,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -390,12 +348,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagUpdate(t *testing.T) { tag_pattern = "version*" } - `, randomID) + `, repoName) check2 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -414,41 +372,27 @@ 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) }, + Providers: testAccProviders, + 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) var deploymentPolicyId string config1 := fmt.Sprintf(` @@ -458,7 +402,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *test } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -481,12 +425,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *test branch_pattern = "release/*" } - `, randomID) + `, repoName) check1 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -509,7 +453,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *test } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -532,12 +476,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyBranchToTagUpdate(t *test tag_pattern = "v*" } - `, randomID) + `, repoName) check2 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -556,41 +500,27 @@ 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) }, + Providers: testAccProviders, + 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) var deploymentPolicyId string config1 := fmt.Sprintf(` @@ -600,7 +530,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -623,12 +553,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test tag_pattern = "v*" } - `, randomID) + `, repoName) check1 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -651,7 +581,7 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -674,12 +604,12 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test branch_pattern = "release/*" } - `, randomID) + `, repoName) check2 := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr( "github_repository_environment_deployment_policy.test", "environment", @@ -698,33 +628,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) }, + Providers: testAccProviders, + 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, + }, + }, }) }) } @@ -732,9 +648,10 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyTagToBranchUpdate(t *test func TestAccGithubRepositoryEnvironmentDeploymentPolicyErrors(t *testing.T) { t.Run("errors when no patterns are set", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -751,39 +668,26 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyErrors(t *testing.T) { repository = github_repository.test.name environment = github_repository_environment.test.environment } - `, 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, - ExpectError: regexp.MustCompile("one of `branch_pattern,tag_pattern` must be specified"), - }, + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("one of `branch_pattern,tag_pattern` must be specified"), }, - }) - } - - t.Run("with an anonymous 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 both patterns are set", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -802,39 +706,26 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyErrors(t *testing.T) { branch_pattern = "main" tag_pattern = "v*" } - `, 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, - ExpectError: regexp.MustCompile("only one of `branch_pattern,tag_pattern` can be specified"), - }, + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("only one of `branch_pattern,tag_pattern` can be specified"), }, - }) - } - - t.Run("with an anonymous 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 an empty branch pattern is set", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -852,39 +743,26 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyErrors(t *testing.T) { environment = github_repository_environment.test.environment branch_pattern = "" } - `, 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, - ExpectError: regexp.MustCompile("`branch_pattern` must be a valid non-empty string"), - }, + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("`branch_pattern` must be a valid non-empty string"), }, - }) - } - - t.Run("with an anonymous 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 an empty tag pattern is set", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" ignore_vulnerability_alerts_during_read = true } @@ -902,31 +780,642 @@ func TestAccGithubRepositoryEnvironmentDeploymentPolicyErrors(t *testing.T) { environment = github_repository_environment.test.environment tag_pattern = "" } - `, 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, - ExpectError: regexp.MustCompile("`tag_pattern` must be a valid non-empty string"), - }, + `, repoName) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + ExpectError: regexp.MustCompile("`tag_pattern` must be a valid non-empty string"), }, - }) - } + }, + }) + }) +} + +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) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment / test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + branch_pattern = "releases/*" + } + + `, repoName) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment / test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + "releases/*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + ), + ) - 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() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, }) + }) + + t.Run("updates the pattern for a branch-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + var deploymentPolicyId string + + config1 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + branch_pattern = "main" + } + + `, repoName) + + check1 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + "main", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + ), + testDeploymentPolicyId("github_repository_environment_deployment_policy.test", &deploymentPolicyId), + ) + + config2 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + branch_pattern = "release/*" + } + + `, repoName) + + check2 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "repository", repoName), + resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "environment", "environment/test"), + resource.TestCheckResourceAttr("github_repository_environment_deployment_policy.test", "branch_pattern", "release/*"), + resource.TestCheckNoResourceAttr("github_repository_environment_deployment_policy.test", "tag_pattern"), + testSameDeploymentPolicyId( + "github_repository_environment_deployment_policy.test", + &deploymentPolicyId, + ), + ) - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, + }, + { + Config: config2, + Check: check2, + }, + }, }) + }) + + t.Run("creates a repository environment with tag-based deployment policy", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` - t.Run("with an organization account", func(t *testing.T) { - testCase(t, organization) + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + tag_pattern = "v*" + } + + `, repoName) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + "v*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + }) + + t.Run("updates the pattern for a tag-based deployment policy", func(t *testing.T) { + var deploymentPolicyId string + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + + config1 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + tag_pattern = "v*" + } + + `, repoName) + + check1 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + "v*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + ), + testDeploymentPolicyId("github_repository_environment_deployment_policy.test", &deploymentPolicyId), + ) + + config2 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + tag_pattern = "version*" + } + + `, repoName) + + check2 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + "version*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + ), + testSameDeploymentPolicyId( + "github_repository_environment_deployment_policy.test", + &deploymentPolicyId, + ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, + }, + { + Config: config2, + Check: check2, + }, + }, + }) + }) + + 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) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + + config1 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + branch_pattern = "release/*" + } + + `, repoName) + + check1 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + "release/*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + ), + testDeploymentPolicyId("github_repository_environment_deployment_policy.test", &deploymentPolicyId), + ) + + config2 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + tag_pattern = "v*" + } + + `, repoName) + + check2 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + "v*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + ), + testNewDeploymentPolicyId( + "github_repository_environment_deployment_policy.test", + &deploymentPolicyId, + ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, + }, + { + Config: config2, + Check: check2, + }, + }, + }) + }) + + 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) + repoName := fmt.Sprintf("%srepo-env-deploy-%s", testResourcePrefix, randomID) + + config1 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + tag_pattern = "v*" + } + + `, repoName) + + check1 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + "v*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + ), + testDeploymentPolicyId("github_repository_environment_deployment_policy.test", &deploymentPolicyId), + ) + + config2 := fmt.Sprintf(` + + data "github_user" "current" { + username = "" + } + + resource "github_repository" "test" { + name = "%s" + ignore_vulnerability_alerts_during_read = true + } + + resource "github_repository_environment" "test" { + repository = github_repository.test.name + environment = "environment/test" + wait_timer = 10000 + reviewers { + users = [data.github_user.current.id] + } + deployment_branch_policy { + protected_branches = false + custom_branch_policies = true + } + } + + resource "github_repository_environment_deployment_policy" "test" { + repository = github_repository.test.name + environment = github_repository_environment.test.environment + branch_pattern = "release/*" + } + + `, repoName) + + check2 := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "repository", + repoName, + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "environment", + "environment/test", + ), + resource.TestCheckResourceAttr( + "github_repository_environment_deployment_policy.test", "branch_pattern", + "release/*", + ), + resource.TestCheckNoResourceAttr( + "github_repository_environment_deployment_policy.test", "tag_pattern", + ), + testNewDeploymentPolicyId( + "github_repository_environment_deployment_policy.test", + &deploymentPolicyId, + ), + ) + + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnauthenticated(t) }, + ProviderFactories: providerFactories, + Steps: []resource.TestStep{ + { + Config: config1, + Check: check1, + }, + { + Config: config2, + Check: check2, + }, + }, }) }) } diff --git a/github/resource_github_repository_environment_test.go b/github/resource_github_repository_environment_test.go index c14a29064d..16d2beb148 100644 --- a/github/resource_github_repository_environment_test.go +++ b/github/resource_github_repository_environment_test.go @@ -9,9 +9,9 @@ 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) + repoName := fmt.Sprintf("%srepo-env-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` data "github_user" "current" { @@ -19,7 +19,7 @@ func TestAccGithubRepositoryEnvironment(t *testing.T) { } resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" visibility = "public" } @@ -38,7 +38,7 @@ func TestAccGithubRepositoryEnvironment(t *testing.T) { } } - `, randomID) + `, repoName) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttr("github_repository_environment.test", "environment", "environment / test"), @@ -47,29 +47,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..0c5c05d01f 100644 --- a/github/resource_github_repository_file_test.go +++ b/github/resource_github_repository_file_test.go @@ -12,14 +12,16 @@ import ( func TestAccGithubRepositoryFile(t *testing.T) { t.Run("creates and manages files", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - + resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true vulnerability_alerts = true } - + resource "github_repository_file" "test" { repository = github_repository.test.name branch = "main" @@ -29,7 +31,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_author = "Terraform User" commit_email = "terraform@example.com" } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_file.test", "content", @@ -60,38 +62,26 @@ 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) + }, }) }) t.Run("can be configured to overwrite files on create", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true - vulnerability_alerts = true + vulnerability_alerts = true } resource "github_repository_file" "test" { @@ -105,7 +95,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_email = "terraform@example.com" } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -133,60 +123,36 @@ 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, + }, + }, }) }) t.Run("creates and manages files on default branch if branch is omitted", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true 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" @@ -194,7 +160,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_author = "Terraform User" commit_email = "terraform@example.com" } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -207,7 +173,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { ), resource.TestCheckResourceAttr( "github_repository_file.test", "ref", - "test", + "main", ), resource.TestCheckResourceAttrSet( "github_repository_file.test", "commit_author", @@ -226,40 +192,28 @@ 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) + }, }) }) t.Run("creates and manages files on auto created branch if branch does not exist", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-file-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true vulnerability_alerts = true } - + resource "github_repository_file" "test" { repository = github_repository.test.name branch = "does/not/exist" @@ -270,7 +224,7 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_email = "terraform@example.com" autocreate_branch = false } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -302,42 +256,30 @@ 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, + }, + }, }) }) t.Run("can delete files from archived repositories without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-file-arch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-file-archive-%s" + name = "%s" auto_init = true } @@ -350,57 +292,47 @@ func TestAccGithubRepositoryFile(t *testing.T) { commit_author = "Terraform User" commit_email = "terraform@example.com" } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)) + `, repoName) archivedConfig := strings.Replace(config, `auto_init = true`, `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" + name = "%s" auto_init = true archived = true } - `, acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum)), - }, + `, 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_repository_milestone_test.go b/github/resource_github_repository_milestone_test.go index 8858124194..30346b94f7 100644 --- a/github/resource_github_repository_milestone_test.go +++ b/github/resource_github_repository_milestone_test.go @@ -9,13 +9,13 @@ 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) + repoName := fmt.Sprintf("%srepo-milestone-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" } resource "github_repository_milestone" "test" { @@ -27,7 +27,7 @@ func TestAccGithubRepositoryMilestone(t *testing.T) { state = "closed" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -36,29 +36,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..8ea8d8ce1e 100644 --- a/github/resource_github_repository_project_test.go +++ b/github/resource_github_repository_project_test.go @@ -10,15 +10,15 @@ 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) + repoName := fmt.Sprintf("%srepo-project-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" has_projects = true } @@ -27,38 +27,24 @@ func TestAccGithubRepositoryProject(t *testing.T) { repository = github_repository.test.name body = "this is a test project" } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestMatchResourceAttr( "github_repository_project.test", "url", - regexp.MustCompile(randomID+"/projects/1"), + regexp.MustCompile(repoName+"/projects/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() { 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..816abd8a07 100644 --- a/github/resource_github_repository_pull_request_test.go +++ b/github/resource_github_repository_pull_request_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubRepositoryPullRequest(t *testing.T) { t.Run("manages the pull request lifecycle", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-pr-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -38,14 +39,14 @@ func TestAccGithubRepositoryPullRequest(t *testing.T) { title = "test title" body = "test body" } - `, randomID) + `, repoName) const resourceName = "github_repository_pull_request.test" check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( resourceName, "base_repository", - fmt.Sprintf("tf-acc-test-%s", randomID), + repoName, ), resource.TestCheckResourceAttr(resourceName, "base_ref", "main"), resource.TestCheckResourceAttr(resourceName, "head_ref", "test"), @@ -63,34 +64,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 5b7cf2c057..f4aec6cd34 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..0a1570bd3f 100644 --- a/github/resource_github_repository_ruleset_test.go +++ b/github/resource_github_repository_ruleset_test.go @@ -13,15 +13,16 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-%s", testResourcePrefix, randomID) - 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" + name = "%s" auto_init = true default_branch = "main" - vulnerability_alerts = true + vulnerability_alerts = true } resource "github_repository_environment" "example" { @@ -95,7 +96,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { non_fast_forward = true } } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -125,44 +126,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: 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) + repoName := fmt.Sprintf("%srepo-ruleset-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = false vulnerability_alerts = true } @@ -194,7 +176,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { } } } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -207,38 +189,33 @@ 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) { - repoName := fmt.Sprintf(`tf-acc-test-rename-%[1]s`, randomID) + t.Run("updates a ruleset name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ruleset-ren-%s", testResourcePrefix, randomID) oldRSName := fmt.Sprintf(`ruleset-%[1]s`, randomID) newRSName := fmt.Sprintf(`%[1]s-renamed`, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "%[1]s" - description = "Terraform acceptance tests %[2]s" + name = "%s" + description = "Terraform acceptance tests %s" vulnerability_alerts = true } resource "github_repository_ruleset" "test" { - name = "%[3]s" + name = "%s" repository = github_repository.test.id target = "branch" enforcement = "active" @@ -264,45 +241,34 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-imp-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-import-%[1]s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true default_branch = "main" vulnerability_alerts = true @@ -371,51 +337,38 @@ func TestGithubRepositoryRulesets(t *testing.T) { non_fast_forward = true } } - `, randomID) + `, repoName, randomID) check := resource.ComposeTestCheckFunc( 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) + repoName := fmt.Sprintf("%srepo-ruleset-push-%s", testResourcePrefix, randomID) - 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" + name = "%s" auto_init = false visibility = "internal" vulnerability_alerts = true @@ -440,7 +393,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { } } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( "github_repository_ruleset.test_push", "name", @@ -463,33 +416,25 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-mq-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-merge-queue-%s" + name = "%s" auto_init = true default_branch = "main" } @@ -519,7 +464,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { } } } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -532,43 +477,40 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-bypass-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-bypass-%s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true } resource "github_team" "test" { - name = "tf-acc-test-team-%[1]s" + name = "%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 +520,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" } @@ -600,75 +542,81 @@ func TestGithubRepositoryRulesets(t *testing.T) { } } } - `, randomID) + `, repoName, randomID, teamName) - 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 = "%s" + description = "Terraform acceptance tests %s" + auto_init = true + } - `, - "", - 1, - ) + resource "github_team" "test" { + name = "%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 + } + } + } + `, repoName, randomID, teamName) - 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) + repoName := fmt.Sprintf("%srepo-ruleset-nobp-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-no-bypass-%s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true } @@ -689,7 +637,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { deletion = true } } - `, randomID) + `, repoName, randomID) configUpdated := strings.Replace( config, @@ -721,57 +669,72 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-bpmod-%s", testResourcePrefix, randomID) + teamAlwaysName := fmt.Sprintf("%steam-always-%s", testResourcePrefix, randomID) + teamPRName := fmt.Sprintf("%steam-pr-%s", testResourcePrefix, randomID) + teamExemptName := fmt.Sprintf("%steam-exempt-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-bypass-modes-%s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true } resource "github_team" "test_always" { - name = "tf-acc-test-team-always-%[1]s" + name = "%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" + name = "%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" + name = "%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 +744,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" } @@ -809,7 +772,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { creation = true } } - `, randomID) + `, repoName, randomID, teamAlwaysName, teamPRName, teamExemptName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -851,43 +814,40 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-bpupd-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-update-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-bypass-update-%s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true } resource "github_team" "test" { - name = "tf-acc-test-team-update-%[1]s" + name = "%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 +857,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" } @@ -913,7 +873,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { creation = true } } - `, randomID) + `, repoName, randomID, teamName) configUpdated := strings.Replace( config, @@ -937,47 +897,44 @@ 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) + repoName := fmt.Sprintf("%srepo-ruleset-actor-%s", testResourcePrefix, randomID) + teamName := fmt.Sprintf("%steam-actor-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-actor-types-%s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %s" auto_init = true } resource "github_team" "test" { - name = "tf-acc-test-team-actor-%[1]s" + name = "%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 +944,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 +956,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 { @@ -1015,7 +972,7 @@ func TestGithubRepositoryRulesets(t *testing.T) { creation = true } } - `, randomID) + `, repoName, randomID, teamName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1023,14 +980,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,56 +1003,43 @@ 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) + }, }) }) } func TestGithubRepositoryRulesetArchived(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("skips update and delete on archived repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ruleset-arch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-archive-%s" + name = "%s" auto_init = true archived = false } + resource "github_repository_ruleset" "test" { name = "test" repository = github_repository.test.name @@ -1103,7 +1047,7 @@ func TestGithubRepositoryRulesetArchived(t *testing.T) { enforcement = "active" rules { creation = true } } - `, randomID) + `, repoName) resource.Test(t, resource.TestCase{ PreCheck: func() { skipUnlessMode(t, individual) }, @@ -1117,9 +1061,11 @@ func TestGithubRepositoryRulesetArchived(t *testing.T) { }) t.Run("prevents creating ruleset on archived repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-ruleset-arch-cr-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-archive-create-%s" + name = "%s" auto_init = true archived = true } @@ -1130,7 +1076,7 @@ func TestGithubRepositoryRulesetArchived(t *testing.T) { enforcement = "active" rules { creation = true } } - `, randomID) + `, repoName) resource.Test(t, resource.TestCase{ PreCheck: func() { skipUnlessMode(t, individual) }, diff --git a/github/resource_github_repository_test.go b/github/resource_github_repository_test.go index 403935e061..513f665b93 100644 --- a/github/resource_github_repository_test.go +++ b/github/resource_github_repository_test.go @@ -1,16 +1,11 @@ package github import ( - "context" - "errors" "fmt" - "log" - "os" "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" @@ -21,13 +16,13 @@ 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) + testRepoName := fmt.Sprintf("%screate-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-create-%[1]s" + name = "%s" description = "Terraform acceptance tests %[1]s" has_discussions = true has_issues = true @@ -42,7 +37,7 @@ func TestAccGithubRepositories(t *testing.T) { auto_init = false web_commit_signoff_required = true } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -67,40 +62,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: 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) { - oldName := fmt.Sprintf(`tf-acc-test-rename-%[1]s`, randomID) - newName := fmt.Sprintf(`%[1]s-renamed`, oldName) + t.Run("updates a repositories name without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + oldName := fmt.Sprintf(`%srename-%s`, testResourcePrefix, randomID) + newName := fmt.Sprintf(`%s-renamed`, oldName) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "%[1]s" - description = "Terraform acceptance tests %[2]s" + name = "%[1]s" + description = "Terraform acceptance tests %[2]s" } `, oldName, randomID) @@ -127,92 +109,68 @@ 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) + testRepoName := fmt.Sprintf("%simport-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-import-%[1]s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %[1]s" auto_init = false } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( 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) + testRepoName := fmt.Sprintf("%sarchive-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-archive-%[1]s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %[1]s" archived = false } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -229,46 +187,34 @@ 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) + testRepoName := fmt.Sprintf("%sproject-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-project-%[1]s" - description = "Terraform acceptance tests %[1]s" + name = "%s" + description = "Terraform acceptance tests %[1]s" has_projects = false } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -285,52 +231,40 @@ 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) + testRepoName := fmt.Sprintf("%sbranch-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-branch-%[1]s" - description = "Terraform acceptance tests %[1]s" - default_branch = "main" - auto_init = true + name = "%s" + description = "Terraform acceptance tests %[1]s" + default_branch = "main" + auto_init = true } resource "github_branch" "default" { - repository = github_repository.test.name - branch = "default" + repository = github_repository.test.name + branch = "default" } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -347,41 +281,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"], + }, + }, }) }) @@ -389,13 +309,15 @@ 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) + testRepoName := fmt.Sprintf("%sempty-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-empty-%[1]s" - description = "Terraform acceptance tests %[1]s" - default_branch = "main" + name = "%s" + description = "Terraform acceptance tests %[1]s" + default_branch = "main" } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -404,50 +326,38 @@ 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) + testRepoName := fmt.Sprintf("%slicense-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-license-%[1]s" + name = "%s" description = "Terraform acceptance tests %[1]s" license_template = "ms-pl" gitignore_template = "C++" } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -460,40 +370,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: 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) + testRepoName := fmt.Sprintf("%stopic-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -502,36 +400,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: 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) + testRepoName := fmt.Sprintf("%stemplate-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-template-%s" + name = "%s" description = "Terraform acceptance tests %[1]s" template { @@ -540,7 +426,7 @@ func TestAccGithubRepositories(t *testing.T) { } } - `, randomID, testOrganization, "terraform-template-module") + `, testRepoName, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -549,41 +435,68 @@ 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("creates a repository using an org 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") - }) + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testRepoName := fmt.Sprintf("%stemplate-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + description = "Terraform acceptance tests %[1]s" - t.Run("with an individual account", func(t *testing.T) { - testCase(t, individual) - }) + template { + owner = "%s" + repository = "%s" + } + + } + `, testRepoName, 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) + testRepoName := fmt.Sprintf("%sdestroy-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-destroy-%[1]s" + name = "%s" auto_init = true archive_on_destroy = true archived = false } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -600,159 +513,111 @@ 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("%spub-vuln-%s", testResourcePrefix, 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("%sprv-vuln-%s", testResourcePrefix, 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) + testRepoName := fmt.Sprintf("%smodify-co-str-%s", testResourcePrefix, randomID) mergeCommitTitle := "PR_TITLE" mergeCommitMessage := "BLANK" updatedMergeCommitTitle := "MERGE_MESSAGE" @@ -760,22 +625,22 @@ func TestAccGithubRepositories(t *testing.T) { configs := map[string]string{ "before": fmt.Sprintf(` - resource "github_repository" "test" { - - name = "tf-acc-test-modify-co-str-%[1]s" - allow_merge_commit = true - merge_commit_title = "%s" - merge_commit_message = "%s" - } - `, randomID, mergeCommitTitle, mergeCommitMessage), + resource "github_repository" "test" { + + name = "%[1]s" + allow_merge_commit = true + merge_commit_title = "%s" + merge_commit_message = "%s" + } + `, testRepoName, mergeCommitTitle, mergeCommitMessage), "after": fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-modify-co-str-%[1]s" - allow_merge_commit = true - merge_commit_title = "%s" - merge_commit_message = "%s" - } - `, randomID, updatedMergeCommitTitle, updatedMergeCommitMessage), + resource "github_repository" "test" { + name = "%[1]s" + allow_merge_commit = true + merge_commit_title = "%s" + merge_commit_message = "%s" + } + `, testRepoName, updatedMergeCommitTitle, updatedMergeCommitMessage), } checks := map[string]resource.TestCheckFunc{ @@ -801,37 +666,25 @@ 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) + testRepoName := fmt.Sprintf("%smodify-sq-str-%s", testResourcePrefix, randomID) squashMergeCommitTitle := "PR_TITLE" squashMergeCommitMessage := "PR_BODY" updatedSquashMergeCommitTitle := "COMMIT_OR_PR_TITLE" @@ -839,21 +692,21 @@ func TestAccGithubRepositories(t *testing.T) { configs := map[string]string{ "before": fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-modify-sq-str-%[1]s" - allow_squash_merge = true - squash_merge_commit_title = "%s" - squash_merge_commit_message = "%s" - } - `, randomID, squashMergeCommitTitle, squashMergeCommitMessage), + resource "github_repository" "test" { + name = "%s" + allow_squash_merge = true + squash_merge_commit_title = "%s" + squash_merge_commit_message = "%s" + } + `, testRepoName, squashMergeCommitTitle, squashMergeCommitMessage), "after": fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-modify-sq-str-%[1]s" - allow_squash_merge = true - squash_merge_commit_title = "%s" - squash_merge_commit_message = "%s" - } - `, randomID, updatedSquashMergeCommitTitle, updatedSquashMergeCommitMessage), + resource "github_repository" "test" { + name = "tf-acc-test-modify-sq-str-%[1]s" + allow_squash_merge = true + squash_merge_commit_title = "%s" + squash_merge_commit_message = "%s" + } + `, randomID, updatedSquashMergeCommitTitle, updatedSquashMergeCommitMessage), } checks := map[string]resource.TestCheckFunc{ @@ -879,376 +732,240 @@ 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) + testRepoName := fmt.Sprintf("%slegacy-pages-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" + name = "%s" auto_init = true pages { + build_type = "legacy" + source { branch = "main" } } } - `, 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, - }, + `, testRepoName) + + 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) + testRepoName := fmt.Sprintf("%sworkflow-pages-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "%s" + auto_init = true + pages { + build_type = "workflow" + } + } + `, testRepoName) + + 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("manages the pages from workflow feature for a repository", func(t *testing.T) { + 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") + } + + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testRepoName := fmt.Sprintf("%ssecurity-private-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-%s" - auto_init = true - pages { - build_type = "workflow" + name = "%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" + } + secret_scanning_push_protection { + status = "enabled" + } + secret_scanning_ai_detection { + status = "enabled" + } + secret_scanning_non_provider_patterns { + status = "enabled" + } } } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( - "github_repository.test", "pages.0.source.0.branch", - "main", + "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, - }, + 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("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") - } - 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(` + t.Run("manages the security feature for a public repository", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testRepoName := fmt.Sprintf("%ssecurity-public-%s", testResourcePrefix, randomID) + 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" - } - secret_scanning_push_protection { - status = "enabled" - } - secret_scanning_ai_detection { - status = "enabled" - } - secret_scanning_non_provider_patterns { - status = "enabled" + name = "%s" + description = "A repository created by Terraform to test security features" + visibility = "public" + security_and_analysis { + secret_scanning { + status = "enabled" + } + # seems like it can only be "enabled" for an organization that has purchased GHAS + secret_scanning_push_protection { + status = "disabled" + } } - } } - `, randomID) + `, testRepoName) - 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) - }) - }) - - t.Run("for a public repository", func(t *testing.T) { - config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-%s" - description = "A repository created by Terraform to test security features" - visibility = "public" - security_and_analysis { - secret_scanning { - status = "enabled" - } - # seems like it can only be "enabled" for an organization that has purchased GHAS - secret_scanning_push_protection { - status = "disabled" - } - } - } - `, 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) + testRepoName := fmt.Sprintf("%svisibility-private-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "private" { - name = "tf-acc-test-visibility-private-%s" + name = "%s" visibility = "private" } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1257,41 +974,27 @@ 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) + testRepoName := fmt.Sprintf("%svisibility-internal-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "internal" { - name = "tf-acc-test-visibility-internal-%s" + name = "%s" visibility = "internal" } - `, randomID) + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1300,40 +1003,28 @@ 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) + testRepoName := fmt.Sprintf("%svisibility-public-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "public" { - name = "tf-acc-test-visibility-public-%s" + name = "%s" visibility = "public" vulnerability_alerts = false } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -1350,43 +1041,31 @@ 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) + testRepoName := fmt.Sprintf("%spublic-vuln-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "test" { - name = "tf-acc-test-prv-vuln-%s" + resource "github_repository" "test" { + name = "%s" visibility = "private" } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -1407,45 +1086,33 @@ 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) + testRepoName := fmt.Sprintf("%sinternal-vuln-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-prv-vuln-%s" + name = "%s" visibility = "private" } - `, randomID) + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -1466,49 +1133,37 @@ 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) + testRepoName := fmt.Sprintf("%stemplate-visibility-private-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "private" { - name = "tf-acc-test-visibility-private-%s" + name = "%s" visibility = "private" template { owner = "%s" repository = "%s" } } - `, randomID, testOrganization, "terraform-template-module") + `, testRepoName, testAccConf.testPublicTemplateRepositoryOwner, testAccConf.testPublicTemplateRepository) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1521,134 +1176,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) - }) }) } @@ -1676,39 +1257,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( @@ -1787,18 +1335,18 @@ func TestGithubRepositoryNameFailsValidationWithSpace(t *testing.T) { } func TestAccGithubRepository_fork(t *testing.T) { - randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) - t.Run("forks a repository without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testRepoName := fmt.Sprintf("%sfork-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` - resource "github_repository" "forked" { - name = "terraform-provider-github-%s" + resource "github_repository" "forked" { + name = "%s" description = "Terraform acceptance test - forked repository %[1]s" fork = true source_owner = "integrations" source_repo = "terraform-provider-github" - } - `, randomID) + } + `, testRepoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -1819,56 +1367,44 @@ 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") + }, }) }) t.Run("can update forked repository properties", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + testRepoName := fmt.Sprintf("%sfork-update-%s", testResourcePrefix, randomID) initialConfig := fmt.Sprintf(` - resource "github_repository" "forked_update" { - name = "terraform-provider-github-update-%s" + resource "github_repository" "forked_update" { + name = "%s" description = "Initial description for forked repo" fork = true source_owner = "integrations" source_repo = "terraform-provider-github" has_wiki = true has_issues = false - } - `, randomID) + } + `, testRepoName) updatedConfig := fmt.Sprintf(` - resource "github_repository" "forked_update" { - name = "terraform-provider-github-update-%s" + resource "github_repository" "forked_update" { + name = "%s" description = "Updated description for forked repo" fork = true source_owner = "integrations" source_repo = "terraform-provider-github" has_wiki = false has_issues = true - } - `, randomID) + } + `, testRepoName) checks := map[string]resource.TestCheckFunc{ "before": resource.ComposeTestCheckFunc( @@ -1901,157 +1437,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 { - baseURL, isGHES, err := getBaseURL(os.Getenv("GITHUB_BASE_URL")) - if err != nil { - return err - } - - config := Config{BaseURL: baseURL, IsGHES: isGHES, 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..69f9a0f216 100644 --- a/github/resource_github_repository_topics_test.go +++ b/github/resource_github_repository_topics_test.go @@ -11,10 +11,11 @@ import ( func TestAccGithubRepositoryTopics(t *testing.T) { t.Run("create repository topics and import them", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-topics-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -22,7 +23,7 @@ func TestAccGithubRepositoryTopics(t *testing.T) { repository = github_repository.test.name topics = ["test", "test-2"] } - `, randomID) + `, repoName) const resourceName = "github_repository_topics.test" @@ -30,43 +31,30 @@ 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, + }, + }, }) }) t.Run("create repository topics and update them", func(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-topics-%s", testResourcePrefix, randomID) configBefore := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -74,11 +62,11 @@ func TestAccGithubRepositoryTopics(t *testing.T) { repository = github_repository.test.name topics = ["test", "test-2"] } - `, randomID) + `, repoName) configAfter := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-%s" + name = "%s" auto_init = true } @@ -86,7 +74,7 @@ func TestAccGithubRepositoryTopics(t *testing.T) { repository = github_repository.test.name topics = ["test", "test-2", "extra-topic"] } - `, randomID) + `, repoName) const resourceName = "github_repository_topics.test" @@ -97,33 +85,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..11eb1f0ce4 100644 --- a/github/resource_github_repository_webhook_test.go +++ b/github/resource_github_repository_webhook_test.go @@ -9,18 +9,18 @@ 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) + repoName := fmt.Sprintf("%srepo-webhook-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests" } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] - repository = "test-%[1]s" + depends_on = [github_repository.test] + repository = "%[1]s" configuration { url = "https://google.de/webhook" @@ -30,7 +30,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { events = ["pull_request"] } - `, randomID) + `, repoName) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -41,42 +41,30 @@ 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) + repoName := fmt.Sprintf("%srepo-webhook-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests" } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] - repository = "test-%[1]s" + depends_on = [github_repository.test] + repository = "%[1]s" configuration { url = "https://google.de/webhook" content_type = "json" @@ -84,53 +72,41 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { } events = ["pull_request"] } - `, randomID) + `, repoName) 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("%s/", repoName), + }, + }, }) }) t.Run("updates repository webhooks without error", func(t *testing.T) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-webhook-%s", testResourcePrefix, randomID) configs := map[string]string{ "before": fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests" } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] - repository = "test-%[1]s" + depends_on = [github_repository.test] + repository = "%[1]s" configuration { url = "https://google.de/webhook" @@ -140,16 +116,16 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { events = ["pull_request"] } - `, randomID), + `, repoName), "after": fmt.Sprintf(` resource "github_repository" "test" { - name = "test-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests" } resource "github_repository_webhook" "test" { - depends_on = ["github_repository.test"] - repository = "test-%[1]s" + depends_on = [github_repository.test] + repository = "%[1]s" configuration { secret = "secret" @@ -160,7 +136,7 @@ func TestAccGithubRepositoryWebhook(t *testing.T) { events = ["pull_request"] } - `, randomID), + `, repoName), } checks := map[string]resource.TestCheckFunc{ @@ -172,33 +148,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..b00a3709cd 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("%steam-members-%s", testResourcePrefix, 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..85be560d06 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 } @@ -220,34 +204,31 @@ func testAccCheckGithubTeamMembershipRoleState(n, expected string, membership *g } func testAccGithubTeamMembershipConfig(randString, username, role string) string { + teamName := fmt.Sprintf("%steam-membership-%s", testResourcePrefix, randString) + teamSlugName := fmt.Sprintf("%s-slug", teamName) 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" + name = "%s" description = "Terraform acc test group" } resource "github_team" "test_team_slug" { - name = "tf-acc-test-team-membership-%s-slug" + name = "%s" description = "Terraform acc test group" } 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) +`, teamName, teamSlugName, 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..718c1bfa99 100644 --- a/github/resource_github_team_repository_test.go +++ b/github/resource_github_team_repository_test.go @@ -10,17 +10,19 @@ 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) + teamName := fmt.Sprintf("%steam-repo-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-team-repo-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-repo-%s" + name = "%s" description = "test" } resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%s" } resource "github_team_repository" "test" { @@ -28,7 +30,7 @@ func TestAccGithubTeamRepository(t *testing.T) { repository = "${github_repository.test.name}" permission = "pull" } - `, randomID) + `, teamName, repoName) checks := map[string]resource.TestCheckFunc{ "pull": resource.ComposeTestCheckFunc( @@ -63,65 +65,55 @@ 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) + teamName := fmt.Sprintf("%steam-repo-slug-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-team-repo-slug-%s", testResourcePrefix, randomID) + config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-repo-%s" + name = "%s" description = "test" } resource "github_repository" "test" { - name = "tf-acc-test-%[1]s" + name = "%s" } resource "github_team_repository" "test" { @@ -129,57 +121,45 @@ func TestAccGithubTeamRepository(t *testing.T) { repository = "${github_repository.test.name}" permission = "pull" } - `, randomID) + `, teamName, repoName) check := resource.ComposeTestCheckFunc( 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, + }, + }, }) }) } func TestAccGithubTeamRepositoryArchivedRepo(t *testing.T) { randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-archive-%s", testResourcePrefix, randomID) + repoName := fmt.Sprintf("%srepo-team-archive-%s", testResourcePrefix, randomID) t.Run("can delete team repository access from archived repositories without error", func(t *testing.T) { config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-archive-%s" + name = "%s" description = "test team for archived repo" } resource "github_repository" "test" { - name = "tf-acc-test-team-archive-%[1]s" + name = "%s" auto_init = true } @@ -188,16 +168,16 @@ func TestAccGithubTeamRepositoryArchivedRepo(t *testing.T) { repository = github_repository.test.name permission = "pull" } - `, randomID) + `, teamName, repoName) archivedConfig := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-archive-%s" + name = "%s" description = "test team for archived repo" } resource "github_repository" "test" { - name = "tf-acc-test-team-archive-%[1]s" + name = "%s" auto_init = true archived = true } @@ -207,51 +187,45 @@ func TestAccGithubTeamRepositoryArchivedRepo(t *testing.T) { repository = github_repository.test.name permission = "pull" } - `, 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", - ), + `, teamName, repoName) + + 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" + name = "%s" description = "test team for archived repo" } resource "github_repository" "test" { - name = "tf-acc-test-team-archive-%[1]s" + name = "%s" auto_init = true archived = true } - `, randomID), - }, + `, teamName, repoName), }, - }) - } - - 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..053440a33f 100644 --- a/github/resource_github_team_settings_test.go +++ b/github/resource_github_team_settings_test.go @@ -10,65 +10,49 @@ 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) + teamName := fmt.Sprintf("%steam-settings-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-repo-%s" + name = "%s" description = "generated by terraform provider automated testing" } resource "github_team_settings" "test" { team_id = "${github_team.test.id}" } - `, randomID) + `, teamName) check := resource.ComposeTestCheckFunc( 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) + teamName := fmt.Sprintf("%steam-settings-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-repo-%s" + name = "%s" description = "generated by terraform provider automated testing" } @@ -80,7 +64,7 @@ func TestCanUpdateTeamSettings(t *testing.T) { notify = true } } - `, randomID) + `, teamName) checks := map[string]resource.TestCheckFunc{ "round_robin": resource.ComposeTestCheckFunc( @@ -109,58 +93,42 @@ 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) + teamName := fmt.Sprintf("%steam-settings-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-test-team-repo-%s" + name = "%s" description = "generated by terraform provider automated testing" } @@ -172,33 +140,19 @@ func TestCannotUseReviewSettingsIfDisabled(t *testing.T) { notify = true } } - `, 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 \[.*\]`), - }, + `, teamName) + + 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..3f5dc32b4d 100644 --- a/github/resource_github_team_sync_group_mapping_test.go +++ b/github/resource_github_team_sync_group_mapping_test.go @@ -13,141 +13,139 @@ 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-sync-%s", testResourcePrefix, randomID) + 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-sync-%s", testResourcePrefix, randomID) + 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-sync-%s", testResourcePrefix, randomID) + 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) { + randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + teamName := fmt.Sprintf("%steam-sync-%s", testResourcePrefix, randomID) + 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 +165,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..2a6273990e 100644 --- a/github/resource_github_team_test.go +++ b/github/resource_github_team_test.go @@ -9,91 +9,77 @@ 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) + teamName := fmt.Sprintf("%steam-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-%s" + name = "%s" } - `, randomID) + `, teamName) check := resource.ComposeTestCheckFunc( 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) + team01Name := fmt.Sprintf("%steam-hier01-%s", testResourcePrefix, randomID) + team02Name := fmt.Sprintf("%steam-hier02-%s", testResourcePrefix, randomID) + team03Name := fmt.Sprintf("%steam-hier03-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "team01" { - name = "tf-acc-team01-%s" + name = "%s" description = "Terraform acc test team01a" privacy = "closed" } resource "github_team" "team02" { - name = "tf-acc-team02-%[1]s" + name = "%s" description = "Terraform acc test team02a" privacy = "closed" parent_team_id = "${github_team.team01.id}" } resource "github_team" "team03" { - name = "tf-acc-team03-%[1]s" + name = "%s" description = "Terraform acc test team03a" privacy = "closed" parent_team_id = "${github_team.team02.slug}" } - `, randomID) + `, team01Name, team02Name, team03Name) config2 := fmt.Sprintf(` resource "github_team" "team01" { - name = "tf-acc-team01-%s" + name = "%s" description = "Terraform acc test team01b" privacy = "closed" } resource "github_team" "team02" { - name = "tf-acc-team02-%[1]s" + name = "%s" description = "Terraform acc test team02b" privacy = "closed" } resource "github_team" "team03" { - name = "tf-acc-team03-%[1]s" + name = "%s" description = "Terraform acc test team03b" privacy = "closed" } - `, randomID) + `, team01Name, team02Name, team03Name) check := resource.ComposeAggregateTestCheckFunc( resource.TestCheckResourceAttrSet("github_team.team02", "parent_team_id"), @@ -109,131 +95,87 @@ 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) + teamName := fmt.Sprintf("%steam-no-maint-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-%s" + name = "%s" create_default_maintainer = false } - `, randomID) + `, teamName) check := resource.ComposeTestCheckFunc( 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) + teamName := fmt.Sprintf("%steam-slug-%s", testResourcePrefix, randomID) + teamNameUpdated := fmt.Sprintf("%s-updated", teamName) + teamNameOther := fmt.Sprintf("%s-other", teamName) config := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-%s" + name = "%s" } - `, randomID) + `, teamName) configUpdated := fmt.Sprintf(` resource "github_team" "test" { - name = "tf-acc-updated-%s" + name = "%s" } resource "github_team" "other" { - name = "tf-acc-other-%s" + name = "%s" description = github_team.test.slug } - `, 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)), - ), - }, + `, teamNameUpdated, teamNameOther) + + 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", teamName), + ), }, - }) - } - - t.Run("with an anonymous 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", teamNameUpdated), + ), + }, + }, }) }) } 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..79a8a3ae9a 100644 --- a/github/resource_github_user_invitation_accepter_test.go +++ b/github/resource_github_user_invitation_accepter_test.go @@ -2,61 +2,61 @@ 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" + randomID := acctest.RandString(5) + repoName := fmt.Sprintf("%srepo-invitation-%s", testResourcePrefix, randomID) + + 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 +64,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 +91,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..8e269af12b 100644 --- a/github/resource_github_workflow_repository_permissions_test.go +++ b/github/resource_github_workflow_repository_permissions_test.go @@ -12,10 +12,11 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { t.Run("test setting of basic workflow repository permissions", func(t *testing.T) { defaultWorkflowPermissions := "read" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-workflow-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -24,7 +25,7 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { default_workflow_permissions = "%s" repository = github_repository.test.name } - `, randomID, defaultWorkflowPermissions) + `, repoName, defaultWorkflowPermissions) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -32,29 +33,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) + }, }) }) @@ -63,10 +50,11 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { canApprovePullRequestReviews := "true" randomID := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + repoName := fmt.Sprintf("%srepo-workflow-perms-%s", testResourcePrefix, randomID) config := fmt.Sprintf(` resource "github_repository" "test" { - name = "tf-acc-test-topic-%[1]s" + name = "%[1]s" description = "Terraform acceptance tests %[1]s" topics = ["terraform", "testing"] } @@ -76,7 +64,7 @@ func TestAccGithubWorkflowRepositoryPermissions(t *testing.T) { can_approve_pull_request_reviews = %s repository = github_repository.test.name } - `, randomID, defaultWorkflowPermissions, canApprovePullRequestReviews) + `, repoName, defaultWorkflowPermissions, canApprovePullRequestReviews) check := resource.ComposeTestCheckFunc( resource.TestCheckResourceAttr( @@ -87,34 +75,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 8cab431d90..0000000000 --- a/github/sweeper_test.go +++ /dev/null @@ -1,42 +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") - } - - baseURL, isGHES, err := getBaseURL(os.Getenv("GITHUB_BASE_URL")) - if err != nil { - return nil, err - } - - config := Config{ - Token: os.Getenv("GITHUB_TOKEN"), - Owner: os.Getenv("GITHUB_OWNER"), - BaseURL: baseURL, - IsGHES: isGHES, - } - - 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/go.mod b/go.mod index ce64ff38d8..b62302fac5 100644 --- a/go.mod +++ b/go.mod @@ -9,6 +9,7 @@ require ( github.com/google/go-github/v67 v67.0.0 github.com/google/uuid v1.6.0 github.com/hashicorp/go-cty v1.5.0 + github.com/hashicorp/terraform-plugin-log v0.9.0 github.com/hashicorp/terraform-plugin-sdk/v2 v2.38.1 github.com/shurcooL/githubv4 v0.0.0-20221126192849-0b5c4c7994eb github.com/stretchr/testify v1.11.1 @@ -129,7 +130,6 @@ require ( github.com/hashicorp/terraform-exec v0.23.1 // indirect github.com/hashicorp/terraform-json v0.27.1 // indirect github.com/hashicorp/terraform-plugin-go v0.29.0 // indirect - github.com/hashicorp/terraform-plugin-log v0.9.0 // indirect github.com/hashicorp/terraform-registry-address v0.4.0 // indirect github.com/hashicorp/terraform-svchost v0.1.1 // indirect github.com/hashicorp/yamux v0.1.2 // indirect