Skip to content

Commit dbc8d96

Browse files
josephdt12apeabody
andauthored
chore: Update CB workspace GH test to use existing repo (#372)
Co-authored-by: Andrew Peabody <andrewpeabody@google.com>
1 parent f8886c4 commit dbc8d96

File tree

3 files changed

+122
-74
lines changed

3 files changed

+122
-74
lines changed

examples/tf_cloudbuild_workspace_simple_github/scripts/push-to-repo.sh

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -40,8 +40,18 @@ git config user.email "terraform-robot@example.com"
4040
git config user.name "TF Robot"
4141
git checkout plan || git checkout -b plan
4242
git add -A
43-
git commit -m "init tf configs"
44-
git push origin plan -f
43+
44+
# The '-z' flag checks if the following string is empty.
45+
if [ -z "$(git status --porcelain)" ]; then
46+
# If the output is empty, the working directory is clean.
47+
echo "No changes to commit. Nothing to do."
48+
else
49+
# If there is output, changes exist, so we commit.
50+
echo "Changes detected. Attempting to commit..."
51+
git commit -m "init tf configs"
52+
git push origin plan -f
53+
fi
54+
4555
sleep 60
4656
git checkout main || git checkout -b main
4757
git merge plan

test/integration/tf_cloudbuild_workspace_simple_github/tf_cloudbuild_workspace_simple_github_test.go

Lines changed: 10 additions & 72 deletions
Original file line numberDiff line numberDiff line change
@@ -26,93 +26,32 @@ import (
2626
"github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test/pkg/git"
2727
"github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test/pkg/tft"
2828
cftutils "github.com/GoogleCloudPlatform/cloud-foundation-toolkit/infra/blueprint-test/pkg/utils"
29-
"github.com/google/go-github/v71/github"
3029
"github.com/stretchr/testify/assert"
3130
"github.com/terraform-google-modules/terraform-google-bootstrap/test/integration/utils"
3231
)
3332

34-
type GitHubClient struct {
35-
t *testing.T
36-
client *github.Client
37-
owner string
38-
repoName string
39-
repository *github.Repository
40-
}
41-
42-
func NewGitHubClient(t *testing.T, token, owner, repo string) *GitHubClient {
43-
t.Helper()
44-
client := github.NewClient(nil).WithAuthToken(token)
45-
return &GitHubClient{
46-
t: t,
47-
client: client,
48-
owner: owner,
49-
repoName: repo,
50-
}
51-
}
52-
53-
func (gh *GitHubClient) GetRepository(ctx context.Context) *github.Repository {
54-
repo, resp, err := gh.client.Repositories.Get(ctx, gh.owner, gh.repoName)
55-
if resp.StatusCode != 404 && err != nil {
56-
gh.t.Fatal(err.Error())
57-
}
58-
gh.repository = repo
59-
return repo
60-
}
61-
62-
func (gh *GitHubClient) CreateRepository(ctx context.Context, org, repoName string) *github.Repository {
63-
newRepo := &github.Repository{
64-
Name: github.String(repoName),
65-
AutoInit: github.Bool(true),
66-
Private: github.Bool(true),
67-
Visibility: github.String("private"),
68-
}
69-
repo, _, err := gh.client.Repositories.Create(ctx, org, newRepo)
70-
if err != nil {
71-
gh.t.Fatal(err.Error())
72-
}
73-
gh.repository = repo
74-
return repo
75-
}
76-
77-
func (gh *GitHubClient) DeleteRepository(ctx context.Context) {
78-
resp, err := gh.client.Repositories.Delete(ctx, gh.owner, *gh.repository.Name)
79-
if resp.StatusCode != 404 && err != nil {
80-
gh.t.Fatal(err.Error())
81-
}
82-
}
33+
const (
34+
githubRepo = "cb-bp-gh"
35+
)
8336

8437
func TestCloudBuildWorkspaceSimpleGitHub(t *testing.T) {
8538
ctx := context.Background()
86-
87-
repoName := fmt.Sprintf("cb-bp-gh-%s", utils.GetRandomStringFromSetup(t))
8839
githubPAT := cftutils.ValFromEnv(t, "IM_GITHUB_PAT")
89-
owner := "im-goose"
90-
client := NewGitHubClient(t, githubPAT, owner, repoName)
91-
92-
repo := client.GetRepository(ctx)
93-
if repo == nil {
94-
client.CreateRepository(ctx, client.owner, client.repoName)
95-
}
40+
client := utils.NewGitHubClient(t, githubPAT, githubRepo)
41+
client.GetRepository(ctx)
9642

9743
// Testing the module's feature of appending the ".git" suffix if it's missing
98-
repoURL := strings.TrimSuffix(client.repository.GetCloneURL(), ".git")
44+
repoURL := strings.TrimSuffix(client.Repository.GetCloneURL(), ".git")
9945
vars := map[string]interface{}{
10046
"github_pat": githubPAT,
10147
"repository_uri": repoURL,
102-
"github_app_id": "47590865", // Found in the URL of your Cloud Build GitHub app configuration settings
48+
"github_app_id": utils.GitHubAppID,
10349
}
10450
bpt := tft.NewTFBlueprintTest(t, tft.WithVars(vars))
10551

10652
bpt.DefineVerify(func(assert *assert.Assertions) {
10753
bpt.DefaultVerify(assert)
10854

109-
t.Cleanup(func() {
110-
// Delete the repository if we hit a failed state
111-
if t.Failed() {
112-
client.DeleteRepository(ctx)
113-
}
114-
})
115-
11655
location := bpt.GetStringOutput("location")
11756
projectID := bpt.GetStringOutput("project_id")
11857

@@ -121,8 +60,8 @@ func TestCloudBuildWorkspaceSimpleGitHub(t *testing.T) {
12160
for _, trigger := range triggers {
12261
triggerOP := utils.LastElement(bpt.GetStringOutput(fmt.Sprintf("cloudbuild_%s_trigger_id", trigger)), "/")
12362
cloudBuildOP := gcloud.Runf(t, "beta builds triggers describe %s --region %s --project %s", triggerOP, location, projectID)
124-
assert.Equal(fmt.Sprintf("%s-%s", repoName, trigger), cloudBuildOP.Get("name").String(), "should have the correct name")
125-
assert.Equal(fmt.Sprintf("projects/%s/serviceAccounts/tf-gh-%s@%s.iam.gserviceaccount.com", projectID, repoName, projectID), cloudBuildOP.Get("serviceAccount").String(), "uses expected SA")
63+
assert.Equal(fmt.Sprintf("%s-%s", githubRepo, trigger), cloudBuildOP.Get("name").String(), "should have the correct name")
64+
assert.Equal(fmt.Sprintf("projects/%s/serviceAccounts/tf-gh-%s@%s.iam.gserviceaccount.com", projectID, githubRepo, projectID), cloudBuildOP.Get("serviceAccount").String(), "uses expected SA")
12665
}
12766

12867
// artifacts, state and log buckets
@@ -157,7 +96,7 @@ func TestCloudBuildWorkspaceSimpleGitHub(t *testing.T) {
15796
}
15897
}
15998

160-
gitRun("clone", fmt.Sprintf("https://%s@github.com/%s/%s", githubPAT, owner, repoName), tmpDir)
99+
gitRun("clone", fmt.Sprintf("https://%s@github.com/%s/%s", githubPAT, utils.GitHubOwner, githubRepo), tmpDir)
161100
gitRun("config", "user.email", "tf-robot@example.com")
162101
gitRun("config", "user.name", "TF Robot")
163102

@@ -209,7 +148,6 @@ func TestCloudBuildWorkspaceSimpleGitHub(t *testing.T) {
209148
bpt.DefineTeardown(func(assert *assert.Assertions) {
210149
// Guarantee clean up even if the normal gcloud/teardown run into errors
211150
t.Cleanup(func() {
212-
client.DeleteRepository(ctx)
213151
bpt.DefaultTeardown(assert)
214152
})
215153
})
Lines changed: 100 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,100 @@
1+
// Copyright 2025 Google LLC
2+
//
3+
// Licensed under the Apache License, Version 2.0 (the "License");
4+
// you may not use this file except in compliance with the License.
5+
// You may obtain a copy of the License at
6+
//
7+
// http://www.apache.org/licenses/LICENSE-2.0
8+
//
9+
// Unless required by applicable law or agreed to in writing, software
10+
// distributed under the License is distributed on an "AS IS" BASIS,
11+
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
// See the License for the specific language governing permissions and
13+
// limitations under the License.
14+
15+
package utils
16+
17+
import (
18+
"context"
19+
"testing"
20+
21+
"github.com/google/go-github/v71/github"
22+
)
23+
24+
const (
25+
GitHubOwner = "im-goose"
26+
GitHubAppID = "47590865" // Found in the URL of your Cloud Build GitHub app configuration settings
27+
)
28+
29+
type GitHubClient struct {
30+
t *testing.T
31+
client *github.Client
32+
owner string
33+
repoName string
34+
Repository *github.Repository
35+
}
36+
37+
func NewGitHubClient(t *testing.T, token, repo string) *GitHubClient {
38+
t.Helper()
39+
client := github.NewClient(nil).WithAuthToken(token)
40+
return &GitHubClient{
41+
t: t,
42+
client: client,
43+
owner: GitHubOwner,
44+
repoName: repo,
45+
}
46+
}
47+
48+
// GetOpenPullRequest gets an open pull request for a given branch if it exists.
49+
func (gh *GitHubClient) GetOpenPullRequest(ctx context.Context, branch string) *github.PullRequest {
50+
opts := &github.PullRequestListOptions{
51+
State: "open",
52+
Head: branch,
53+
}
54+
prs, resp, err := gh.client.PullRequests.List(ctx, gh.owner, gh.repoName, opts)
55+
if resp.StatusCode != 422 && err != nil {
56+
gh.t.Fatal(err.Error())
57+
}
58+
if len(prs) == 0 {
59+
return nil
60+
}
61+
return prs[0]
62+
}
63+
64+
func (gh *GitHubClient) CreatePullRequest(ctx context.Context, title, branch, base string) *github.PullRequest {
65+
newPR := &github.NewPullRequest{
66+
Title: github.String(title),
67+
Head: github.String(branch),
68+
Base: github.String(base),
69+
}
70+
pr, _, err := gh.client.PullRequests.Create(ctx, gh.owner, gh.repoName, newPR)
71+
if err != nil {
72+
gh.t.Fatal(err.Error())
73+
}
74+
return pr
75+
}
76+
77+
func (gh *GitHubClient) MergePullRequest(ctx context.Context, pr *github.PullRequest, commitTitle, commitMessage string) *github.PullRequestMergeResult {
78+
result, _, err := gh.client.PullRequests.Merge(ctx, gh.owner, gh.repoName, *pr.Number, commitMessage, nil)
79+
if err != nil {
80+
gh.t.Fatal(err.Error())
81+
}
82+
return result
83+
}
84+
85+
func (gh *GitHubClient) ClosePullRequest(ctx context.Context, pr *github.PullRequest) {
86+
pr.State = github.String("closed")
87+
_, _, err := gh.client.PullRequests.Edit(ctx, gh.owner, gh.repoName, *pr.Number, pr)
88+
if err != nil {
89+
gh.t.Fatal(err.Error())
90+
}
91+
}
92+
93+
func (gh *GitHubClient) GetRepository(ctx context.Context) *github.Repository {
94+
repo, resp, err := gh.client.Repositories.Get(ctx, gh.owner, gh.repoName)
95+
if resp.StatusCode != 404 && err != nil {
96+
gh.t.Fatal(err.Error())
97+
}
98+
gh.Repository = repo
99+
return repo
100+
}

0 commit comments

Comments
 (0)