Skip to content

Commit

Permalink
cli: refactor tests: use TestMain, t.Setenv
Browse files Browse the repository at this point in the history
  • Loading branch information
alexandear committed Nov 2, 2023
1 parent 573f715 commit f93b45e
Showing 1 changed file with 11 additions and 9 deletions.
20 changes: 11 additions & 9 deletions cli/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,34 +7,36 @@ import (
"github.com/spf13/afero"
)

func init() {
func TestMain(m *testing.M) {
os.Unsetenv("HOME")
os.Unsetenv("XDG_CONFIG_HOME")
AppFs = afero.NewMemMapFs()
os.Exit(m.Run())
}

func TestXDGConfigDirIsPrefferedFirst(t *testing.T) {
t.Cleanup(func() {
// reset fs after test
AppFs = afero.NewMemMapFs()
})

xdgDirPath := "/tmp-iofs/xdg/config"
homeDirPath := "/tmp-iofs/home/tester"
AppFs.MkdirAll(xdgDirPath, 0755)
AppFs.MkdirAll(homeDirPath, 0755)

afero.WriteFile(AppFs, xdgDirPath+"/revive.toml", []byte("\n"), 0644)
os.Setenv("XDG_CONFIG_HOME", xdgDirPath)
t.Setenv("XDG_CONFIG_HOME", xdgDirPath)

afero.WriteFile(AppFs, homeDirPath+"/revive.toml", []byte("\n"), 0644)
os.Setenv("HOME", homeDirPath)
t.Setenv("HOME", homeDirPath)

got := buildDefaultConfigPath()
want := xdgDirPath + "/revive.toml"

if got != want {
t.Errorf("got %q, wanted %q", got, want)
}

//reset fs after test
AppFs = afero.NewMemMapFs()
}

func TestHomeConfigDir(t *testing.T) {
Expand All @@ -43,7 +45,7 @@ func TestHomeConfigDir(t *testing.T) {
AppFs.MkdirAll(homeDirPath, 0755)

afero.WriteFile(AppFs, homeDirPath+"/revive.toml", []byte("\n"), 0644)
os.Setenv("HOME", homeDirPath)
t.Setenv("HOME", homeDirPath)

got := buildDefaultConfigPath()
want := homeDirPath + "/revive.toml"
Expand All @@ -58,7 +60,7 @@ func TestXDGConfigDir(t *testing.T) {
AppFs.MkdirAll(xdgDirPath, 0755)

afero.WriteFile(AppFs, xdgDirPath+"/revive.toml", []byte("\n"), 0644)
os.Setenv("XDG_CONFIG_HOME", xdgDirPath)
t.Setenv("XDG_CONFIG_HOME", xdgDirPath)

got := buildDefaultConfigPath()
want := xdgDirPath + "/revive.toml"
Expand All @@ -70,7 +72,7 @@ func TestXDGConfigDir(t *testing.T) {

func TestXDGConfigDirNoFile(t *testing.T) {
xdgDirPath := "/tmp-iofs/xdg/config"
os.Setenv("XDG_CONFIG_HOME", xdgDirPath)
t.Setenv("XDG_CONFIG_HOME", xdgDirPath)

got := buildDefaultConfigPath()
want := xdgDirPath + "/revive.toml"
Expand Down

0 comments on commit f93b45e

Please sign in to comment.