diff --git a/common/utils.go b/common/utils.go index 0ea402d..90b62d4 100644 --- a/common/utils.go +++ b/common/utils.go @@ -88,9 +88,7 @@ func InitConfig(config interface{}) { break } } - if cont == nil { - dtmcli.LogFatalf("no config file conf.yml/conf.sample.yml found in current and parent path: %s", MustGetwd()) - } + dtmcli.LogIfFatalf(cont == nil, "no config file conf.yml/conf.sample.yml found in current and parent path: %s", MustGetwd()) dtmcli.Logf("cont is: \n%s", string(cont)) err := yaml.Unmarshal(cont, config) dtmcli.FatalIfError(err) diff --git a/dtmcli/utils.go b/dtmcli/utils.go index 7815756..545a9fa 100644 --- a/dtmcli/utils.go +++ b/dtmcli/utils.go @@ -126,19 +126,25 @@ func LogRedf(fmt string, args ...interface{}) { Logf("\x1b[31m\n"+fmt+"\x1b[0m\n", args...) } +// FatalExitFunc Fatal退出函数,测试时被替换 +var FatalExitFunc = func() { os.Exit(1) } + // LogFatalf 采用红色打印错误类信息, 并退出 func LogFatalf(fmt string, args ...interface{}) { Logf("\x1b[31m\n"+fmt+"\x1b[0m\n", args...) - os.Exit(1) + FatalExitFunc() +} + +// LogIfFatalf 采用红色打印错误类信息, 并退出 +func LogIfFatalf(condition bool, fmt string, args ...interface{}) { + if condition { + LogFatalf(fmt, args...) + } } // FatalIfError 采用红色打印错误类信息, 并退出 func FatalIfError(err error) { - if err == nil { - return - } - Logf("\x1b[31m\nFatal error: %v\x1b[0m\n", err) - os.Exit(1) + LogIfFatalf(err == nil, "Fatal error: %v", err) } // RestyClient the resty object diff --git a/dtmcli/utils_test.go b/dtmcli/utils_test.go index 2ed3320..a67485e 100644 --- a/dtmcli/utils_test.go +++ b/dtmcli/utils_test.go @@ -2,6 +2,7 @@ package dtmcli import ( "errors" + "fmt" "os" "strings" "testing" @@ -76,3 +77,15 @@ func TestSome(t *testing.T) { s2 := MayReplaceLocalhost("http://localhost") assert.Equal(t, "http://localhost", s2) } + +func TestFatal(t *testing.T) { + old := FatalExitFunc + defer func() { + FatalExitFunc = old + }() + FatalExitFunc = func() { panic(fmt.Errorf("fatal")) } + err := CatchP(func() { + LogIfFatalf(true, "") + }) + assert.Error(t, err, fmt.Errorf("fatal")) +}