浏览代码

improve test coverage for debug

Jackson Tian 7 年之前
父节点
当前提交
cfd8ed355e
共有 2 个文件被更改,包括 52 次插入2 次删除
  1. 10 2
      sdk/utils/debug.go
  2. 42 0
      sdk/utils/debug_test.go

+ 10 - 2
sdk/utils/debug.go

@@ -8,10 +8,18 @@ import (
 
 type Debug func(format string, v ...interface{})
 
+var hookGetEnv = func() string {
+	return os.Getenv("DEBUG")
+}
+
+var hookPrint = func(input string) {
+	fmt.Println(input)
+}
+
 func Init(flag string) Debug {
 	enable := false
 
-	env := os.Getenv("DEBUG")
+	env := hookGetEnv()
 	parts := strings.Split(env, ",")
 	for _, part := range parts {
 		if part == flag {
@@ -22,7 +30,7 @@ func Init(flag string) Debug {
 
 	return func(format string, v ...interface{}) {
 		if enable {
-			fmt.Println(fmt.Sprintf(format, v...))
+			hookPrint(fmt.Sprintf(format, v...))
 		}
 	}
 }

+ 42 - 0
sdk/utils/debug_test.go

@@ -2,9 +2,51 @@ package utils
 
 import (
 	"testing"
+
+	"github.com/stretchr/testify/assert"
 )
 
 func TestMain(t *testing.T) {
 	debug := Init("sdk")
 	debug("%s", "testing")
 }
+
+func TestMain_Matched(t *testing.T) {
+	originLookGetEnv := hookGetEnv
+	originhookPrint := hookPrint
+	defer func() {
+		hookGetEnv = originLookGetEnv
+		hookPrint = originhookPrint
+	}()
+	hookGetEnv = func() string {
+		return "sdk"
+	}
+	output := ""
+	hookPrint = func(input string) {
+		output = input
+		originhookPrint(input)
+	}
+	debug := Init("sdk")
+	debug("%s", "testing")
+	assert.Equal(t, "testing", output)
+}
+
+func TestMain_UnMatched(t *testing.T) {
+	originLookGetEnv := hookGetEnv
+	originhookPrint := hookPrint
+	defer func() {
+		hookGetEnv = originLookGetEnv
+		hookPrint = originhookPrint
+	}()
+	hookGetEnv = func() string {
+		return "non-sdk"
+	}
+	output := ""
+	hookPrint = func(input string) {
+		output = input
+		originhookPrint(input)
+	}
+	debug := Init("sdk")
+	debug("%s", "testing")
+	assert.Equal(t, "", output)
+}