forked from ava-labs/avalanchego
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconfig_test.go
349 lines (316 loc) · 10.9 KB
/
config_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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
// (c) 2019-2020, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package config
import (
"fmt"
"io/ioutil"
"log"
"os"
"path"
"path/filepath"
"testing"
"github.com/spf13/pflag"
"github.com/spf13/viper"
"github.com/stretchr/testify/assert"
"github.com/ava-labs/avalanchego/chains"
"github.com/ava-labs/avalanchego/ids"
)
func TestSetChainConfigs(t *testing.T) {
tests := map[string]struct {
configs map[string]string
upgrades map[string]string
corethConfig string
errMessage string
expected map[string]chains.ChainConfig
}{
"no chain configs": {
configs: map[string]string{},
upgrades: map[string]string{},
expected: map[string]chains.ChainConfig{},
},
"valid chain-id": {
configs: map[string]string{"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp": "hello", "2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm": "world"},
upgrades: map[string]string{"yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp": "helloUpgrades"},
expected: func() map[string]chains.ChainConfig {
m := map[string]chains.ChainConfig{}
id1, err := ids.FromString("yH8D7ThNJkxmtkuv2jgBa4P1Rn3Qpr4pPr7QYNfcdoS6k6HWp")
assert.NoError(t, err)
m[id1.String()] = chains.ChainConfig{Config: []byte("hello"), Upgrade: []byte("helloUpgrades")}
id2, err := ids.FromString("2JVSBoinj9C2J33VntvzYtVJNZdN2NKiwwKjcumHUWEb5DbBrm")
assert.NoError(t, err)
m[id2.String()] = chains.ChainConfig{Config: []byte("world"), Upgrade: []byte(nil)}
return m
}(),
},
"valid alias": {
configs: map[string]string{"C": "hello", "X": "world"},
upgrades: map[string]string{"C": "upgradess"},
expected: func() map[string]chains.ChainConfig {
m := map[string]chains.ChainConfig{}
m["C"] = chains.ChainConfig{Config: []byte("hello"), Upgrade: []byte("upgradess")}
m["X"] = chains.ChainConfig{Config: []byte("world"), Upgrade: []byte(nil)}
return m
}(),
},
"coreth config only": {
configs: map[string]string{},
upgrades: map[string]string{},
corethConfig: "hello",
expected: map[string]chains.ChainConfig{"C": {Config: []byte("hello"), Upgrade: []byte(nil)}},
},
"coreth with c alias chain config": {
configs: map[string]string{"C": "hello", "X": "world"},
upgrades: map[string]string{"C": "upgradess"},
corethConfig: "hellocoreth",
errMessage: "is already provided",
expected: nil,
},
"coreth with evm alias chain config": {
configs: map[string]string{"evm": "hello", "X": "world"},
upgrades: map[string]string{"evm": "upgradess"},
corethConfig: "hellocoreth",
errMessage: "is already provided",
expected: nil,
},
"coreth and c chain upgrades in config": {
configs: map[string]string{"X": "world"},
upgrades: map[string]string{"C": "upgradess"},
corethConfig: "hello",
expected: func() map[string]chains.ChainConfig {
m := map[string]chains.ChainConfig{}
m["C"] = chains.ChainConfig{Config: []byte("hello"), Upgrade: []byte("upgradess")}
m["X"] = chains.ChainConfig{Config: []byte("world"), Upgrade: []byte(nil)}
return m
}(),
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
var configJSON string
if len(test.corethConfig) > 0 {
configJSON = fmt.Sprintf(`{%q: %q, %q: %q}`, ChainConfigDirKey, root, CorethConfigKey, test.corethConfig)
} else {
configJSON = fmt.Sprintf(`{%q: %q}`, ChainConfigDirKey, root)
}
configFile := setupConfigJSON(t, root, configJSON)
chainsDir := root
// Create custom configs
for key, value := range test.configs {
chainDir := path.Join(chainsDir, key)
setupFile(t, chainDir, chainConfigFileName+".ex", value)
}
for key, value := range test.upgrades {
chainDir := path.Join(chainsDir, key)
setupFile(t, chainDir, chainUpgradeFileName+".ex", value)
}
v := setupViper(configFile)
// Parse config
assert.Equal(root, v.GetString(ChainConfigDirKey))
chainConfigs, err := getChainConfigs(v)
if len(test.errMessage) > 0 {
assert.Error(err)
if err != nil {
assert.Contains(err.Error(), test.errMessage)
}
} else {
assert.NoError(err)
}
assert.Equal(test.expected, chainConfigs)
})
}
}
func TestSetChainConfigsDirNotExist(t *testing.T) {
tests := map[string]struct {
structure string
file map[string]string
err error
errMessage string
expected map[string]chains.ChainConfig
}{
"cdir not exist": {
structure: "/",
file: map[string]string{"config.ex": "noeffect"},
err: os.ErrNotExist,
expected: nil,
},
"cdir is file ": {
structure: "/",
file: map[string]string{"cdir": "noeffect"},
errMessage: "not a directory",
expected: nil,
},
"chain subdir not exist": {
structure: "/cdir/",
file: map[string]string{"config.ex": "noeffect"},
expected: map[string]chains.ChainConfig{},
},
"full structure": {
structure: "/cdir/C/",
file: map[string]string{"config.ex": "hello"},
expected: map[string]chains.ChainConfig{"C": {Config: []byte("hello"), Upgrade: []byte(nil)}},
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
chainConfigDir := path.Join(root, "cdir")
configJSON := fmt.Sprintf(`{%q: %q}`, ChainConfigDirKey, chainConfigDir)
configFile := setupConfigJSON(t, root, configJSON)
dirToCreate := path.Join(root, test.structure)
assert.NoError(os.MkdirAll(dirToCreate, 0o700))
for key, value := range test.file {
setupFile(t, dirToCreate, key, value)
}
v := setupViper(configFile)
// Parse config
assert.Equal(chainConfigDir, v.GetString(ChainConfigDirKey))
// don't read with getConfigFromViper since it's very slow.
chainConfigs, err := getChainConfigs(v)
switch {
case test.err != nil:
assert.ErrorIs(err, test.err)
case len(test.errMessage) > 0:
assert.Error(err)
assert.Contains(err.Error(), test.errMessage)
default:
assert.NoError(err)
assert.Equal(test.expected, chainConfigs)
}
})
}
}
func TestSetChainConfigDefaultDir(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
// changes internal package variable, since using defaultDir (under user home) is risky.
defaultChainConfigDir = path.Join(root, "cdir")
configFilePath := setupConfigJSON(t, root, "{}")
v := setupViper(configFilePath)
assert.Equal(defaultChainConfigDir, v.GetString(ChainConfigDirKey))
chainsDir := path.Join(defaultChainConfigDir, "C")
setupFile(t, chainsDir, chainConfigFileName+".ex", "helloworld")
chainConfigs, err := getChainConfigs(v)
assert.NoError(err)
expected := map[string]chains.ChainConfig{"C": {Config: []byte("helloworld"), Upgrade: []byte(nil)}}
assert.Equal(expected, chainConfigs)
}
func TestReadVMAliases(t *testing.T) {
tests := map[string]struct {
givenJSON string
expected map[ids.ID][]string
errMessage string
}{
"wrong vm id": {
givenJSON: `{"wrongVmId": ["vm1","vm2"]}`,
expected: nil,
errMessage: "problem unmarshaling vmAliases",
},
"vm id": {
givenJSON: `{"2Ctt6eGAeo4MLqTmGa7AdRecuVMPGWEX9wSsCLBYrLhX4a394i": ["vm1","vm2"],
"Gmt4fuNsGJAd2PX86LBvycGaBpgCYKbuULdCLZs3SEs1Jx1LU": ["vm3", "vm4"] }`,
expected: func() map[ids.ID][]string {
m := map[ids.ID][]string{}
id1, _ := ids.FromString("2Ctt6eGAeo4MLqTmGa7AdRecuVMPGWEX9wSsCLBYrLhX4a394i")
id2, _ := ids.FromString("Gmt4fuNsGJAd2PX86LBvycGaBpgCYKbuULdCLZs3SEs1Jx1LU")
m[id1] = []string{"vm1", "vm2"}
m[id2] = []string{"vm3", "vm4"}
return m
}(),
errMessage: "",
},
}
for name, test := range tests {
t.Run(name, func(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
aliasPath := path.Join(root, "aliases.json")
configJSON := fmt.Sprintf(`{%q: %q}`, VMAliasesFileKey, aliasPath)
configFilePath := setupConfigJSON(t, root, configJSON)
setupFile(t, root, "aliases.json", test.givenJSON)
v := setupViper(configFilePath)
vmAliases, err := readVMAliases(v)
if len(test.errMessage) > 0 {
assert.Error(err)
assert.Contains(err.Error(), test.errMessage)
} else {
assert.NoError(err)
assert.Equal(test.expected, vmAliases)
}
})
}
}
func TestReadVMAliasesDefaultDir(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
// changes internal package variable, since using defaultDir (under user home) is risky.
defaultVMAliasFilePath = filepath.Join(root, "aliases.json")
configFilePath := setupConfigJSON(t, root, "{}")
v := setupViper(configFilePath)
assert.Equal(defaultVMAliasFilePath, v.GetString(VMAliasesFileKey))
setupFile(t, root, "aliases.json", `{"2Ctt6eGAeo4MLqTmGa7AdRecuVMPGWEX9wSsCLBYrLhX4a394i": ["vm1","vm2"]}`)
vmAliases, err := readVMAliases(v)
assert.NoError(err)
expected := map[ids.ID][]string{}
id, _ := ids.FromString("2Ctt6eGAeo4MLqTmGa7AdRecuVMPGWEX9wSsCLBYrLhX4a394i")
expected[id] = []string{"vm1", "vm2"}
assert.Equal(expected, vmAliases)
}
func TestReadVMAliasesDirNotExists(t *testing.T) {
assert := assert.New(t)
root := t.TempDir()
aliasPath := "/not/exists"
// set it explicitly
configJSON := fmt.Sprintf(`{%q: %q}`, VMAliasesFileKey, aliasPath)
configFilePath := setupConfigJSON(t, root, configJSON)
v := setupViper(configFilePath)
vmAliases, err := readVMAliases(v)
assert.Nil(vmAliases)
assert.Error(err)
assert.Contains(err.Error(), "vm alias file does not exist")
// do not set it explicitly
configJSON = "{}"
configFilePath = setupConfigJSON(t, root, configJSON)
v = setupViper(configFilePath)
vmAliases, err = readVMAliases(v)
assert.Nil(vmAliases)
assert.NoError(err)
}
// setups config json file and writes content
func setupConfigJSON(t *testing.T, rootPath string, value string) string {
configFilePath := path.Join(rootPath, "config.json")
assert.NoError(t, ioutil.WriteFile(configFilePath, []byte(value), 0o600))
return configFilePath
}
// setups file creates necessary path and writes value to it.
func setupFile(t *testing.T, path string, fileName string, value string) {
assert.NoError(t, os.MkdirAll(path, 0o700))
filePath := filepath.Join(path, fileName)
assert.NoError(t, ioutil.WriteFile(filePath, []byte(value), 0o600))
}
func setupViper(configFilePath string) *viper.Viper {
v := viper.New()
fs := BuildFlagSet()
pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.PanicOnError) // flags are now reset
pflag.CommandLine.AddGoFlagSet(fs)
pflag.Parse()
if err := v.BindPFlags(pflag.CommandLine); err != nil {
log.Fatal(err)
}
// need to set it since in tests executable dir is somewhere /var/tmp/ (or wherever is designated by go)
// thus it searches buildDir in /var/tmp/
// but actual buildDir resides under project_root/build
currentPath, err := os.Getwd()
if err != nil {
log.Fatal(err)
}
v.Set(BuildDirKey, filepath.Join(currentPath, "..", "build"))
v.SetConfigFile(configFilePath)
err = v.ReadInConfig()
if err != nil {
log.Fatal(err)
}
return v
}