test: use T.Setenv to set env vars in tests (#189)

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>
This commit is contained in:
Eng Zer Jun
2022-06-30 09:15:34 +09:00
committed by GitHub
parent a5b7c2b08d
commit ce3b81e2a1
8 changed files with 20 additions and 52 deletions
+3 -11
View File
@@ -26,16 +26,9 @@ type tmplTestCase struct {
}
// setEnvs sets the environment variables for the test case
func (t *tmplTestCase) setEnvs() {
func (t *tmplTestCase) setEnvs(tt *testing.T) {
for k, v := range t.envs {
os.Setenv(k, v)
}
}
// unSetEnvs unsets the environment variables for the test case
func (t *tmplTestCase) unSetEnvs() {
for k := range t.envs {
os.Unsetenv(k)
tt.Setenv(k, v)
}
}
@@ -235,8 +228,7 @@ func TestTmplStrings(t *testing.T) {
for _, tc := range tmplE2eTest.tcs {
t.Run(tc.name, func(t *testing.T) {
tc.setEnvs()
defer tc.unSetEnvs()
tc.setEnvs(t)
tmpl, err := tmpl.Parse(tc.tmplString)
require.Nilf(t, err, "error parsing template: %v", err)