forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util_test.go
440 lines (356 loc) · 13.3 KB
/
util_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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
package server_test
import (
"context"
"errors"
"fmt"
"os"
"path"
"path/filepath"
"strings"
"testing"
"github.com/spf13/cobra"
"github.com/stretchr/testify/require"
tmcfg "github.com/tendermint/tendermint/config"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/config"
"github.com/cosmos/cosmos-sdk/simapp"
sdkerrors "github.com/cosmos/cosmos-sdk/types/errors"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
)
var cancelledInPreRun = errors.New("Cancelled in prerun")
// Used in each test to run the function under test via Cobra
// but to always halt the command
func preRunETestImpl(cmd *cobra.Command, args []string) error {
err := server.InterceptConfigsPreRunHandler(cmd, "", nil, tmcfg.DefaultConfig())
if err != nil {
return err
}
return cancelledInPreRun
}
func TestInterceptConfigsPreRunHandlerCreatesConfigFilesWhenMissing(t *testing.T) {
tempDir := t.TempDir()
cmd := server.StartCmd(nil, "/foobar")
if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil {
t.Fatalf("Could not set home flag [%T] %v", err, err)
}
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
// Test that config.toml is created
configTomlPath := path.Join(tempDir, "config", "config.toml")
s, err := os.Stat(configTomlPath)
if err != nil {
t.Fatalf("Could not stat config.toml after run %v", err)
}
if !s.Mode().IsRegular() {
t.Fatal("config.toml not created as regular file")
}
if s.Size() == 0 {
t.Fatal("config.toml created as empty file")
}
// Test that tendermint config is initialized
if serverCtx.Config == nil {
t.Fatal("tendermint config not created")
}
// Test that app.toml is created
appTomlPath := path.Join(tempDir, "config", "app.toml")
s, err = os.Stat(appTomlPath)
if err != nil {
t.Fatalf("Could not stat app.toml after run %v", err)
}
if !s.Mode().IsRegular() {
t.Fatal("appp.toml not created as regular file")
}
if s.Size() == 0 {
t.Fatal("config.toml created as empty file")
}
// Test that the config for use in server/start.go is created
if serverCtx.Viper == nil {
t.Error("app config Viper instance not created")
}
}
func TestInterceptConfigsPreRunHandlerReadsConfigToml(t *testing.T) {
const testDbBackend = "awesome_test_db"
tempDir := t.TempDir()
err := os.Mkdir(path.Join(tempDir, "config"), os.ModePerm)
if err != nil {
t.Fatalf("creating config dir failed: %v", err)
}
configTomlPath := path.Join(tempDir, "config", "config.toml")
writer, err := os.Create(configTomlPath)
if err != nil {
t.Fatalf("creating config.toml file failed: %v", err)
}
_, err = writer.WriteString(fmt.Sprintf("db-backend = '%s'\n", testDbBackend))
if err != nil {
t.Fatalf("Failed writing string to config.toml: %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("Failed closing config.toml: %v", err)
}
cmd := server.StartCmd(nil, "/foobar")
if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil {
t.Fatalf("Could not set home flag [%T] %v", err, err)
}
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if testDbBackend != serverCtx.Config.DBBackend {
t.Error("backend was not set from config.toml")
}
}
func TestInterceptConfigsPreRunHandlerReadsAppToml(t *testing.T) {
const testHaltTime = 1337
tempDir := t.TempDir()
err := os.Mkdir(path.Join(tempDir, "config"), os.ModePerm)
if err != nil {
t.Fatalf("creating config dir failed: %v", err)
}
appTomlPath := path.Join(tempDir, "config", "app.toml")
writer, err := os.Create(appTomlPath)
if err != nil {
t.Fatalf("creating app.toml file failed: %v", err)
}
_, err = writer.WriteString(fmt.Sprintf("halt-time = %d\n", testHaltTime))
if err != nil {
t.Fatalf("Failed writing string to app.toml: %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("Failed closing app.toml: %v", err)
}
cmd := server.StartCmd(nil, tempDir)
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if testHaltTime != serverCtx.Viper.GetInt("halt-time") {
t.Error("Halt time was not set from app.toml")
}
}
func TestInterceptConfigsPreRunHandlerReadsFlags(t *testing.T) {
const testAddr = "tcp://127.1.2.3:12345"
tempDir := t.TempDir()
cmd := server.StartCmd(nil, "/foobar")
if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil {
t.Fatalf("Could not set home flag [%T] %v", err, err)
}
// This flag is added by tendermint
if err := cmd.Flags().Set("rpc.laddr", testAddr); err != nil {
t.Fatalf("Could not set address flag [%T] %v", err, err)
}
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if testAddr != serverCtx.Config.RPC.ListenAddress {
t.Error("RPCListenAddress was not set from command flags")
}
}
func TestInterceptConfigsPreRunHandlerReadsEnvVars(t *testing.T) {
const testAddr = "tcp://127.1.2.3:12345"
tempDir := t.TempDir()
cmd := server.StartCmd(nil, "/foobar")
if err := cmd.Flags().Set(flags.FlagHome, tempDir); err != nil {
t.Fatalf("Could not set home flag [%T] %v", err, err)
}
executableName, err := os.Executable()
if err != nil {
t.Fatalf("Could not get executable name: %v", err)
}
basename := path.Base(executableName)
basename = strings.ReplaceAll(basename, ".", "_")
// This is added by tendermint
envVarName := fmt.Sprintf("%s_RPC_LADDR", strings.ToUpper(basename))
os.Setenv(envVarName, testAddr)
t.Cleanup(func() {
os.Unsetenv(envVarName)
})
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if testAddr != serverCtx.Config.RPC.ListenAddress {
t.Errorf("RPCListenAddress was not set from env. var. %q", envVarName)
}
}
/*
The following tests are here to check the precedence of each
of the configuration sources. A common setup functionality is used
to avoid duplication of code between tests.
*/
var (
TestAddrExpected = "tcp://127.126.125.124:12345" // expected to be used in test
TestAddrNotExpected = "tcp://127.127.127.127:11111" // not expected to be used in test
)
type precedenceCommon struct {
envVarName string
flagName string
configTomlPath string
cmd *cobra.Command
}
func newPrecedenceCommon(t *testing.T) precedenceCommon {
retval := precedenceCommon{}
// Determine the env. var. name based off the executable name
executableName, err := os.Executable()
if err != nil {
t.Fatalf("Could not get executable name: %v", err)
}
basename := path.Base(executableName)
basename = strings.ReplaceAll(basename, ".", "_")
basename = strings.ReplaceAll(basename, "-", "_")
// Store the name of the env. var.
retval.envVarName = fmt.Sprintf("%s_RPC_LADDR", strings.ToUpper(basename))
// Store the flag name. This flag is added by tendermint
retval.flagName = "rpc.laddr"
// Create a tempdir and create './config' under that
tempDir := t.TempDir()
err = os.Mkdir(path.Join(tempDir, "config"), os.ModePerm)
if err != nil {
t.Fatalf("creating config dir failed: %v", err)
}
// Store the path for config.toml
retval.configTomlPath = path.Join(tempDir, "config", "config.toml")
// always remove the env. var. after each test execution
t.Cleanup(func() {
// This should not fail but if it does just panic
if err := os.Unsetenv(retval.envVarName); err != nil {
panic("Could not clear configuration env. var. used in test")
}
})
// Set up the command object that is used in this test
retval.cmd = server.StartCmd(nil, tempDir)
retval.cmd.PreRunE = preRunETestImpl
return retval
}
func (v precedenceCommon) setAll(t *testing.T, setFlag *string, setEnvVar *string, setConfigFile *string) {
if setFlag != nil {
if err := v.cmd.Flags().Set(v.flagName, *setFlag); err != nil {
t.Fatalf("Failed setting flag %q", v.flagName)
}
}
if setEnvVar != nil {
os.Setenv(v.envVarName, *setEnvVar)
}
if setConfigFile != nil {
writer, err := os.Create(v.configTomlPath)
if err != nil {
t.Fatalf("creating config.toml file failed: %v", err)
}
_, err = writer.WriteString(fmt.Sprintf("[rpc]\nladdr = \"%s\"\n", *setConfigFile))
if err != nil {
t.Fatalf("Failed writing string to config.toml: %v", err)
}
if err := writer.Close(); err != nil {
t.Fatalf("Failed closing config.toml: %v", err)
}
}
}
func TestInterceptConfigsPreRunHandlerPrecedenceFlag(t *testing.T) {
testCommon := newPrecedenceCommon(t)
testCommon.setAll(t, &TestAddrExpected, &TestAddrNotExpected, &TestAddrNotExpected)
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if TestAddrExpected != serverCtx.Config.RPC.ListenAddress {
t.Fatalf("RPCListenAddress was not set from flag %q", testCommon.flagName)
}
}
func TestInterceptConfigsPreRunHandlerPrecedenceEnvVar(t *testing.T) {
testCommon := newPrecedenceCommon(t)
testCommon.setAll(t, nil, &TestAddrExpected, &TestAddrNotExpected)
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if TestAddrExpected != serverCtx.Config.RPC.ListenAddress {
t.Errorf("RPCListenAddress was not set from env. var. %q", testCommon.envVarName)
}
}
func TestInterceptConfigsPreRunHandlerPrecedenceConfigFile(t *testing.T) {
testCommon := newPrecedenceCommon(t)
testCommon.setAll(t, nil, nil, &TestAddrExpected)
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if TestAddrExpected != serverCtx.Config.RPC.ListenAddress {
t.Errorf("RPCListenAddress was not read from file %q", testCommon.configTomlPath)
}
}
func TestInterceptConfigsPreRunHandlerPrecedenceConfigDefault(t *testing.T) {
testCommon := newPrecedenceCommon(t)
// Do not set anything
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := testCommon.cmd.ExecuteContext(ctx); err != cancelledInPreRun {
t.Fatalf("function failed with [%T] %v", err, err)
}
if "tcp://127.0.0.1:26657" != serverCtx.Config.RPC.ListenAddress {
t.Error("RPCListenAddress is not using default")
}
}
// Ensure that if interceptConfigs encounters any error other than non-existen errors
// that we correctly return the offending error, for example a permission error.
// See https://github.com/cosmos/cosmos-sdk/issues/7578
func TestInterceptConfigsWithBadPermissions(t *testing.T) {
tempDir := t.TempDir()
subDir := filepath.Join(tempDir, "nonPerms")
if err := os.Mkdir(subDir, 0600); err != nil {
t.Fatalf("Failed to create sub directory: %v", err)
}
cmd := server.StartCmd(nil, "/foobar")
if err := cmd.Flags().Set(flags.FlagHome, subDir); err != nil {
t.Fatalf("Could not set home flag [%T] %v", err, err)
}
cmd.PreRunE = preRunETestImpl
serverCtx := &server.Context{}
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
if err := cmd.ExecuteContext(ctx); !os.IsPermission(err) {
t.Fatalf("Failed to catch permissions error, got: [%T] %v", err, err)
}
}
func TestEmptyMinGasPrices(t *testing.T) {
tempDir := t.TempDir()
err := os.Mkdir(filepath.Join(tempDir, "config"), os.ModePerm)
require.NoError(t, err)
encCfg := simapp.MakeTestEncodingConfig()
// Run InitCmd to create necessary config files.
clientCtx := client.Context{}.WithHomeDir(tempDir).WithCodec(encCfg.Codec)
serverCtx := server.NewDefaultContext()
ctx := context.WithValue(context.Background(), server.ServerContextKey, serverCtx)
ctx = context.WithValue(ctx, client.ClientContextKey, &clientCtx)
cmd := genutilcli.InitCmd(simapp.ModuleBasics, tempDir)
cmd.SetArgs([]string{"appnode-test"})
err = cmd.ExecuteContext(ctx)
require.NoError(t, err)
// Modify app.toml.
appCfgTempFilePath := filepath.Join(tempDir, "config", "app.toml")
appConf := config.DefaultConfig()
appConf.BaseConfig.MinGasPrices = ""
config.WriteConfigFile(appCfgTempFilePath, appConf)
// Run StartCmd.
cmd = server.StartCmd(nil, tempDir)
cmd.PreRunE = func(cmd *cobra.Command, _ []string) error {
return server.InterceptConfigsPreRunHandler(cmd, "", nil, tmcfg.DefaultConfig())
}
err = cmd.ExecuteContext(ctx)
require.Errorf(t, err, sdkerrors.ErrAppConfig.Error())
}