-
Notifications
You must be signed in to change notification settings - Fork 0
/
env_test.go
121 lines (109 loc) · 2.64 KB
/
env_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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package confcrypt_test
import (
"os"
"strings"
"testing"
"github.com/WqyJh/confcrypt"
"github.com/stretchr/testify/assert"
)
type Nested struct {
A string
B []string
C int
D map[string][]string
}
type Config struct {
A, B string
C int
D map[int]string
E map[string]Nested
F string
G []string
}
func getData(t *testing.T, key string) (origin Config, expected Config) {
t.Helper()
expected = Config{
A: RandString(10),
B: RandString(128),
C: 1,
D: map[int]string{
2: RandString(20),
8: RandString(44),
},
E: map[string]Nested{
"a": {
A: RandString(33),
B: []string{RandString(10), RandString(20)},
C: 1,
D: map[string][]string{
"b": {RandString(10), RandString(20)},
},
},
},
F: RandString(20),
G: []string{RandString(10), RandString(20)},
}
origin = Config{
A: encryptString(t, expected.A, key),
B: encryptString(t, expected.B, key),
C: expected.C,
D: map[int]string{
2: encryptString(t, expected.D[2], key),
8: encryptString(t, expected.D[8], key),
},
E: map[string]Nested{
"a": {
A: encryptString(t, expected.E["a"].A, key),
B: []string{
encryptString(t, expected.E["a"].B[0], key),
encryptString(t, expected.E["a"].B[1], key),
},
C: expected.E["a"].C,
D: map[string][]string{
"b": {
encryptString(t, expected.E["a"].D["b"][0], key),
encryptString(t, expected.E["a"].D["b"][1], key),
},
},
},
},
F: expected.F,
G: []string{
encryptString(t, expected.G[0], key),
expected.G[1],
},
}
return
}
func TestDecodeInplace(t *testing.T) {
key := RandString(64)
origin, expected := getData(t, key)
assert.NotEqual(t, expected, origin)
err := confcrypt.DecodeInplace(&origin, key)
assert.NoError(t, err)
assert.Equal(t, expected, origin)
}
func TestDecodeByEnv(t *testing.T) {
key := RandString(64)
origin, expected := getData(t, key)
assert.NotEqual(t, expected, origin)
err := confcrypt.DecodeByEnv(&origin)
assert.True(t, strings.Contains(err.Error(), "empty key"))
os.Setenv("CONFIG_KEY", key)
err = confcrypt.DecodeByEnv(&origin)
assert.NoError(t, err)
assert.Equal(t, expected, origin)
// reinitialize
origin, expected = getData(t, key)
assert.NotEqual(t, expected, origin)
err = confcrypt.DecodeByEnv(&origin, confcrypt.WithEnv("CONFIG_KEY_2"))
assert.True(t, strings.Contains(err.Error(), "empty key"))
os.Setenv("CONFIG_KEY_2", key)
err = confcrypt.DecodeByEnv(&origin, confcrypt.WithEnv("CONFIG_KEY_2"))
assert.NoError(t, err)
assert.Equal(t, expected, origin)
os.Unsetenv("CONFIG_KEY")
os.Unsetenv("CONFIG_KEY_2")
err = confcrypt.DecodeByEnv(&expected)
assert.NoError(t, err)
}