From e695d4c4195ca405d6f34fd7babe922609a8e9c9 Mon Sep 17 00:00:00 2001 From: Hannes Gustafsson Date: Tue, 29 Oct 2024 10:32:03 +0000 Subject: [PATCH] Fix flaky test TestCommitStatusTargetURL (#39) The test added in [1] uses environment variables in a parallel test which causes it to be flaky and sometimes fail as is described in [2]. To fix the flaky test, the environment variable is pulled out and read in the caller of the function under test, so that it can be tested without reading the global environment variable. [1] a43d3d17e100dd2400dca4969acd159ba7f1cb84 [2] https://pkg.go.dev/testing#T.Setenv --- internal/pkg/githubapi/github.go | 7 ++++--- internal/pkg/githubapi/github_test.go | 5 +---- 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/internal/pkg/githubapi/github.go b/internal/pkg/githubapi/github.go index 1306ce9..b7a1fe8 100644 --- a/internal/pkg/githubapi/github.go +++ b/internal/pkg/githubapi/github.go @@ -854,7 +854,9 @@ func SetCommitStatus(ghPrClientDetails GhPrClientDetails, state string) { tcontext := "telefonistka" avatarURL := "https://avatars.githubusercontent.com/u/1616153?s=64" description := "Telefonistka GitOps Bot" - targetURL := commitStatusTargetURL(time.Now()) + tmplFile := os.Getenv("CUSTOM_COMMIT_STATUS_URL_TEMPLATE_PATH") + + targetURL := commitStatusTargetURL(time.Now(), tmplFile) commitStatus := &github.RepoStatus{ TargetURL: &targetURL, @@ -1273,10 +1275,9 @@ func GetFileContent(ghPrClientDetails GhPrClientDetails, branch string, filePath // If the template file is not found or an error occurs during template execution, // it returns a default URL. // passed parameter commitTime can be used in the template as .CommitTime -func commitStatusTargetURL(commitTime time.Time) string { +func commitStatusTargetURL(commitTime time.Time, tmplFile string) string { const targetURL string = "https://github.com/wayfair-incubator/telefonistka" - tmplFile := os.Getenv("CUSTOM_COMMIT_STATUS_URL_TEMPLATE_PATH") tmplName := filepath.Base(tmplFile) // dynamic parameters to be used in the template diff --git a/internal/pkg/githubapi/github_test.go b/internal/pkg/githubapi/github_test.go index 4644528..c5d6caf 100644 --- a/internal/pkg/githubapi/github_test.go +++ b/internal/pkg/githubapi/github_test.go @@ -395,15 +395,12 @@ func TestCommitStatusTargetURL(t *testing.T) { expectedURL := tc.expectedURL if tc.templateFile != "" { - os.Setenv("CUSTOM_COMMIT_STATUS_URL_TEMPLATE_PATH", tc.templateFile) - defer os.Unsetenv("CUSTOM_COMMIT_STATUS_URL_TEMPLATE_PATH") - if tc.validTemplate { expectedURL = fmt.Sprintf(expectedURL, now.UnixMilli(), now.Add(-10*time.Minute).UnixMilli()) } } - result := commitStatusTargetURL(now) + result := commitStatusTargetURL(now, tc.templateFile) if result != expectedURL { t.Errorf("%s: Expected URL to be %q, got %q", name, expectedURL, result) }