Skip to content

Commit

Permalink
up: test - add new env mock util func, fix some test error
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere committed Sep 5, 2022
1 parent 1711db9 commit 9ebc0e0
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 12 deletions.
13 changes: 4 additions & 9 deletions envutil/info_test.go
Expand Up @@ -51,10 +51,11 @@ func TestIsConsole(t *testing.T) {
func TestIsSupportColor(t *testing.T) {
is := assert.New(t)

// clear all OS env
testutil.ClearOSEnv()
defer testutil.RevertOSEnv()

// IsSupport256Color
oldVal := os.Getenv("TERM")
_ = os.Unsetenv("TERM")
// is.False(envutil.IsSupportColor())
is.False(envutil.IsSupport256Color())

// ConEmuANSI
Expand Down Expand Up @@ -85,10 +86,4 @@ func TestIsSupportColor(t *testing.T) {

is.NoErr(os.Setenv("TERM", "xterm-vt220"))
is.True(envutil.IsSupportColor())
// revert
if oldVal != "" {
is.NoErr(os.Setenv("TERM", oldVal))
} else {
is.NoErr(os.Unsetenv("TERM"))
}
}
2 changes: 1 addition & 1 deletion stdutil/convert_test.go
Expand Up @@ -15,7 +15,7 @@ func TestMustString(t *testing.T) {

assert.PanicsErrMsg(t, func() {
stdutil.MustString([]string{"a", "b"})
}, "convert data type is failure")
}, comdef.ErrConvType.Error())
}

func TestToString(t *testing.T) {
Expand Down
23 changes: 21 additions & 2 deletions testutil/envmock.go
Expand Up @@ -77,13 +77,32 @@ func MockOsEnv(mp map[string]string, fn func()) {
MockCleanOsEnv(mp, fn)
}

// backup os ENV
var envBak = os.Environ()

// ClearOSEnv info.
//
// Usage:
//
// testutil.ClearOSEnv()
// defer testutil.RevertOSEnv()
// // do something ...
func ClearOSEnv() { os.Clearenv() }

// RevertOSEnv info
func RevertOSEnv() {
os.Clearenv()
for _, str := range envBak {
nodes := strings.SplitN(str, "=", 2)
_ = os.Setenv(nodes[0], nodes[1])
}
}

// MockCleanOsEnv by env map data.
//
// will clear all old ENV data, use given data map.
// will recover old ENV after fn run.
func MockCleanOsEnv(mp map[string]string, fn func()) {
envBak := os.Environ()

os.Clearenv()
for key, val := range mp {
_ = os.Setenv(key, val)
Expand Down

0 comments on commit 9ebc0e0

Please sign in to comment.