forked from CatchZeng/dingtalk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
configs_test.go
79 lines (65 loc) · 1.6 KB
/
configs_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package configs
import (
"bou.ke/monkey"
"errors"
"github.com/mitchellh/go-homedir"
"github.com/spf13/viper"
"testing"
)
func TestInitConfig(t *testing.T) {
t.Run("homedir.Dir() return error", func(t *testing.T) {
monkey.Patch(homedir.Dir, func() (string, error) {
return "", errors.New("homedir error")
})
shouldPanic(t, InitConfig)
})
t.Run("viper.ReadInConfig() return error", func(t *testing.T) {
monkey.Patch(homedir.Dir, func() (string, error) {
return "/catchzeng", nil
})
monkey.Patch(viper.ReadInConfig, func() error {
return errors.New("ReadInConfig error")
})
InitConfig()
})
t.Run("viper.ReadInConfig() return nil", func(t *testing.T) {
monkey.Patch(homedir.Dir, func() (string, error) {
return "/catchzeng", nil
})
monkey.Patch(viper.ReadInConfig, func() error {
return nil
})
InitConfig()
})
}
func shouldPanic(t *testing.T, f func()) {
defer func() {
if r := recover(); r == nil {
t.Errorf("should have panicked")
}
}()
f()
}
func TestGetConfig(t *testing.T) {
t.Run("viper.ReadInConfig() return error", func(t *testing.T) {
monkey.Patch(viper.ReadInConfig, func() error {
return errors.New("ReadInConfig error")
})
key := "123"
if _, err := GetConfig(key); err == nil {
t.Error("GetConfig error")
}
})
t.Run("viper.ReadInConfig() return nil", func(t *testing.T) {
monkey.Patch(viper.ReadInConfig, func() error {
return nil
})
monkey.Patch(viper.GetString, func(key string) string {
return key
})
key := "456"
if value, err := GetConfig(key); err != nil || value != key {
t.Error("GetConfig error")
}
})
}