test: use t.Setenv to set env vars in tests (#6333)

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>

Signed-off-by: Eng Zer Jun <engzerjun@gmail.com>
This commit is contained in:
Eng Zer Jun 2022-09-26 16:46:02 +08:00 committed by GitHub
parent 9aafd0da13
commit 471cbea4fa
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
9 changed files with 16 additions and 86 deletions

View file

@ -1,24 +1,14 @@
package git
import (
"os"
"reflect"
"testing"
"github.com/cli/cli/v2/internal/run"
)
func setGitDir(t *testing.T, dir string) {
// TODO: also set XDG_CONFIG_HOME, GIT_CONFIG_NOSYSTEM
old_GIT_DIR := os.Getenv("GIT_DIR")
os.Setenv("GIT_DIR", dir)
t.Cleanup(func() {
os.Setenv("GIT_DIR", old_GIT_DIR)
})
}
func TestLastCommit(t *testing.T) {
setGitDir(t, "./fixtures/simple.git")
t.Setenv("GIT_DIR", "./fixtures/simple.git")
c, err := LastCommit()
if err != nil {
t.Fatalf("LastCommit error: %v", err)
@ -32,7 +22,7 @@ func TestLastCommit(t *testing.T) {
}
func TestCommitBody(t *testing.T) {
setGitDir(t, "./fixtures/simple.git")
t.Setenv("GIT_DIR", "./fixtures/simple.git")
body, err := CommitBody("6f1a2405cace1633d89a79c74c65f22fe78f9659")
if err != nil {
t.Fatalf("CommitBody error: %v", err)