feat: automatically SetMode to TestMode when run go test. (#3139)

related issue: https://github.com/gin-gonic/gin/issues/3134
This commit is contained in:
micanzhang 2022-05-14 09:11:35 +08:00 committed by GitHub
parent 90e7073d56
commit ef687e0db2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 1 deletions

View File

@ -5,6 +5,7 @@
package gin package gin
import ( import (
"flag"
"io" "io"
"os" "os"
@ -54,8 +55,12 @@ func init() {
// SetMode sets gin mode according to input string. // SetMode sets gin mode according to input string.
func SetMode(value string) { func SetMode(value string) {
if value == "" { if value == "" {
if flag.Lookup("test.v") != nil {
value = TestMode
} else {
value = DebugMode value = DebugMode
} }
}
switch value { switch value {
case DebugMode: case DebugMode:

View File

@ -5,6 +5,7 @@
package gin package gin
import ( import (
"flag"
"os" "os"
"testing" "testing"
@ -21,9 +22,16 @@ func TestSetMode(t *testing.T) {
assert.Equal(t, TestMode, Mode()) assert.Equal(t, TestMode, Mode())
os.Unsetenv(EnvGinMode) os.Unsetenv(EnvGinMode)
SetMode("")
assert.Equal(t, testCode, ginMode)
assert.Equal(t, TestMode, Mode())
tmp := flag.CommandLine
flag.CommandLine = flag.NewFlagSet("", flag.ContinueOnError)
SetMode("") SetMode("")
assert.Equal(t, debugCode, ginMode) assert.Equal(t, debugCode, ginMode)
assert.Equal(t, DebugMode, Mode()) assert.Equal(t, DebugMode, Mode())
flag.CommandLine = tmp
SetMode(DebugMode) SetMode(DebugMode)
assert.Equal(t, debugCode, ginMode) assert.Equal(t, debugCode, ginMode)