Skip to content

Commit

Permalink
test: use T.Setenv to set env vars in tests
Browse files Browse the repository at this point in the history
This commit replaces `os.Setenv` with `t.Setenv` in tests. The
environment variable is automatically restored to its original value
when the test and all its subtests complete.

Reference: https://pkg.go.dev/testing#T.Setenv
Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
  • Loading branch information
Juneezee authored and tekton-robot committed Sep 3, 2022
1 parent 0fe2931 commit 5185382
Show file tree
Hide file tree
Showing 8 changed files with 20 additions and 79 deletions.
7 changes: 1 addition & 6 deletions pkg/apis/config/artifact_bucket_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package config_test

import (
"os"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -79,12 +78,8 @@ func TestGetArtifactBucketConfigName(t *testing.T) {
expected: "config-artifact-bucket-test",
}} {
t.Run(tc.description, func(t *testing.T) {
original := os.Getenv("CONFIG_ARTIFACT_BUCKET_NAME")
defer t.Cleanup(func() {
os.Setenv("CONFIG_ARTIFACT_BUCKET_NAME", original)
})
if tc.artifactsBucketEnvValue != "" {
os.Setenv("CONFIG_ARTIFACT_BUCKET_NAME", tc.artifactsBucketEnvValue)
t.Setenv("CONFIG_ARTIFACT_BUCKET_NAME", tc.artifactsBucketEnvValue)
}
got := config.GetArtifactBucketConfigName()
want := tc.expected
Expand Down
7 changes: 1 addition & 6 deletions pkg/apis/config/artifact_pvc_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package config_test

import (
"os"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -77,12 +76,8 @@ func TestGetArtifactPVCConfigName(t *testing.T) {
expected: "config-artifact-pvc-test",
}} {
t.Run(tc.description, func(t *testing.T) {
original := os.Getenv("CONFIG_ARTIFACT_PVC_NAME")
defer t.Cleanup(func() {
os.Setenv("CONFIG_ARTIFACT_PVC_NAME", original)
})
if tc.artifactsPVCEnvValue != "" {
os.Setenv("CONFIG_ARTIFACT_PVC_NAME", tc.artifactsPVCEnvValue)
t.Setenv("CONFIG_ARTIFACT_PVC_NAME", tc.artifactsPVCEnvValue)
}
got := config.GetArtifactPVCConfigName()
want := tc.expected
Expand Down
7 changes: 1 addition & 6 deletions pkg/apis/config/feature_flags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ limitations under the License.
package config_test

import (
"os"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -142,12 +141,8 @@ func TestGetFeatureFlagsConfigName(t *testing.T) {
expected: "feature-flags-test",
}} {
t.Run(tc.description, func(t *testing.T) {
original := os.Getenv("CONFIG_FEATURE_FLAGS_NAME")
defer t.Cleanup(func() {
os.Setenv("CONFIG_FEATURE_FLAGS_NAME", original)
})
if tc.featureFlagEnvValue != "" {
os.Setenv("CONFIG_FEATURE_FLAGS_NAME", tc.featureFlagEnvValue)
t.Setenv("CONFIG_FEATURE_FLAGS_NAME", tc.featureFlagEnvValue)
}
got := config.GetFeatureFlagsConfigName()
want := tc.expected
Expand Down
8 changes: 4 additions & 4 deletions pkg/credentials/dockercreds/creds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestFlagHandling(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -103,7 +103,7 @@ func TestFlagHandlingTwice(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -281,7 +281,7 @@ func TestMultipleFlagHandling(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -313,7 +313,7 @@ func TestNoAuthProvided(t *testing.T) {
if err != nil {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}
os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down
10 changes: 5 additions & 5 deletions pkg/credentials/gitcreds/creds_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func TestBasicFlagHandling(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -117,7 +117,7 @@ func TestBasicFlagHandlingTwice(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -209,7 +209,7 @@ func TestSSHFlagHandling(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -294,7 +294,7 @@ func TestSSHFlagHandlingThrice(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down Expand Up @@ -472,7 +472,7 @@ func TestBasicBackslashInUsername(t *testing.T) {
t.Fatalf("flag.CommandLine.Parse() = %v", err)
}

os.Setenv("HOME", credentials.VolumePath)
t.Setenv("HOME", credentials.VolumePath)
if err := NewBuilder().Write(credentials.VolumePath); err != nil {
t.Fatalf("Write() = %v", err)
}
Expand Down
34 changes: 4 additions & 30 deletions pkg/git/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
Expand All @@ -29,27 +29,10 @@ import (

const fileMode = 0755 // rwxr-xr-x

func withTemporaryGitConfig(t *testing.T) func() {
func withTemporaryGitConfig(t *testing.T) {
gitConfigDir := t.TempDir()
key := "GIT_CONFIG_GLOBAL"
t.Helper()
oldValue, envVarExists := os.LookupEnv(key)
if err := os.Setenv(key, filepath.Join(gitConfigDir, "config")); err != nil {
t.Fatal(err)
}
clean := func() {
t.Helper()
if !envVarExists {
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
return
}
if err := os.Setenv(key, oldValue); err != nil {
t.Fatal(err)
}
}
return clean
t.Setenv(key, filepath.Join(gitConfigDir, "config"))
}

func TestValidateGitSSHURLFormat(t *testing.T) {
Expand Down Expand Up @@ -264,8 +247,7 @@ func TestEnsureHomeEnv(t *testing.T) {
homeenv = t.TempDir()
}
if tt.homeenvSet {
cleanup := setEnv("HOME", homeenv, t)
defer cleanup()
t.Setenv("HOME", homeenv)
}
// Create SSH creds directory in directory specified by HOME envvar
if err := os.MkdirAll(filepath.Join(homeenv, ".ssh"), fileMode); err != nil {
Expand Down Expand Up @@ -432,14 +414,6 @@ func createTempGit(t *testing.T, logger *zap.SugaredLogger, gitDir string, submo
}
}

func setEnv(key, value string, t *testing.T) func() {
previous := os.Getenv(key)
if err := os.Setenv(key, value); err != nil {
t.Errorf("Error setting env var %s to %s: %v", key, value, err)
}
return func() { os.Setenv(key, previous) }
}

func checkLogMessage(logMessage string, log *observer.ObservedLogs, logLine int, t *testing.T) {
if logMessage != "" {
allLogLines := log.All()
Expand Down
21 changes: 2 additions & 19 deletions pkg/resolution/resolver/git/resolver_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -627,27 +627,10 @@ func writeAndCommitToTestRepo(t *testing.T, worktree *git.Worktree, repoDir stri
}

// withTemporaryGitConfig resets the .gitconfig for the duration of the test.
func withTemporaryGitConfig(t *testing.T) func() {
func withTemporaryGitConfig(t *testing.T) {
gitConfigDir := t.TempDir()
key := "GIT_CONFIG_GLOBAL"
t.Helper()
oldValue, envVarExists := os.LookupEnv(key)
if err := os.Setenv(key, filepath.Join(gitConfigDir, "config")); err != nil {
t.Fatal(err)
}
clean := func() {
t.Helper()
if !envVarExists {
if err := os.Unsetenv(key); err != nil {
t.Fatal(err)
}
return
}
if err := os.Setenv(key, oldValue); err != nil {
t.Fatal(err)
}
}
return clean
t.Setenv(key, filepath.Join(gitConfigDir, "config"))
}

func createRequest(repoURL, pathInRepo, revision, specificCommit string, useNthCommit int, commitsByBranch map[string][]string) *v1alpha1.ResolutionRequest {
Expand Down
5 changes: 2 additions & 3 deletions test/pullrequest/e2e_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,8 +84,7 @@ func TestPullRequest(t *testing.T) {
// If provided, set the AUTH_TOKEN environment variable that the
// pullrequest binary expects.
if tc.token != "" {
os.Setenv("AUTH_TOKEN", tc.token)
defer os.Unsetenv("AUTH_TOKEN")
t.Setenv("AUTH_TOKEN", tc.token)
}

if *proxy {
Expand Down Expand Up @@ -138,7 +137,7 @@ func startProxy(t *testing.T, dataPath string, header http.Header) {
fmt.Println("http.Serve:", err)
}
}()
os.Setenv("http_proxy", l.Addr().String())
t.Setenv("http_proxy", l.Addr().String())
}

// updateDeps makes sure command is installed locally to resolve any
Expand Down

0 comments on commit 5185382

Please sign in to comment.