-
Notifications
You must be signed in to change notification settings - Fork 3.8k
/
Copy pathexport_test.go
350 lines (271 loc) · 9.03 KB
/
export_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
package server_test
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"testing"
"time"
"cosmossdk.io/log"
cmtcfg "github.com/cometbft/cometbft/config"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
cmttypes "github.com/cometbft/cometbft/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/server"
"github.com/cosmos/cosmos-sdk/server/types"
"github.com/cosmos/cosmos-sdk/testutil/cmdtest"
"github.com/cosmos/cosmos-sdk/types/module"
genutilcli "github.com/cosmos/cosmos-sdk/x/genutil/client/cli"
genutiltypes "github.com/cosmos/cosmos-sdk/x/genutil/types"
"github.com/rs/zerolog"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
)
// ExportSystem wraps a (*cmdtest).System
// and sets up appropriate client and server contexts,
// to simplify testing the export CLI.
type ExportSystem struct {
sys *cmdtest.System
Ctx context.Context
Sctx *server.Context
Cctx client.Context
HomeDir string
}
// newExportSystem returns a cmdtest.System with export as a child command,
// and it returns a context.Background with an associated *server.Context value.
func NewExportSystem(t *testing.T, exporter types.AppExporter) *ExportSystem {
t.Helper()
homeDir := t.TempDir()
// Unclear why we have to create the config directory ourselves,
// but tests fail without this.
if err := os.MkdirAll(filepath.Join(homeDir, "config"), 0o700); err != nil {
t.Fatal(err)
}
sys := cmdtest.NewSystem()
sys.AddCommands(
server.ExportCmd(exporter, homeDir),
genutilcli.InitCmd(module.NewBasicManager(), homeDir),
)
tw := zerolog.NewTestWriter(t)
tw.Frame = 5 // Seems to be the magic number to get source location to match logger calls.
sCtx := server.NewContext(
viper.New(),
cmtcfg.DefaultConfig(),
log.NewCustomLogger(zerolog.New(tw)),
)
sCtx.Config.SetRoot(homeDir)
cCtx := (client.Context{}).WithHomeDir(homeDir)
ctx := context.WithValue(context.Background(), server.ServerContextKey, sCtx)
ctx = context.WithValue(ctx, client.ClientContextKey, &cCtx)
return &ExportSystem{
sys: sys,
Ctx: ctx,
Sctx: sCtx,
Cctx: cCtx,
HomeDir: homeDir,
}
}
// Run wraps (*cmdtest.System).RunC, providing e's context.
func (s *ExportSystem) Run(args ...string) cmdtest.RunResult {
return s.sys.RunC(s.Ctx, args...)
}
// MustRun wraps (*cmdtest.System).MustRunC, providing e's context.
func (s *ExportSystem) MustRun(t *testing.T, args ...string) cmdtest.RunResult {
return s.sys.MustRunC(t, s.Ctx, args...)
}
// isZeroExportedApp reports whether all fields of a are unset.
//
// This is for the mockExporter to check if a return value was ever set.
func isZeroExportedApp(a types.ExportedApp) bool {
return a.AppState == nil &&
len(a.Validators) == 0 &&
a.Height == 0 &&
a.ConsensusParams == cmtproto.ConsensusParams{}
}
// mockExporter provides an Export method matching server/types.AppExporter,
// and it tracks relevant arguments when that method is called.
type mockExporter struct {
// The values to return from Export().
ExportApp types.ExportedApp
Err error
// Whether Export was called at all.
WasCalled bool
// Called tracks the interesting arguments passed to Export().
Called struct {
Height int64
ForZeroHeight bool
JailAllowedAddrs []string
ModulesToExport []string
}
}
// SetDefaultExportApp sets a valid ExportedApp to be returned
// when e.Export is called.
func (e *mockExporter) SetDefaultExportApp() {
e.ExportApp = types.ExportedApp{
ConsensusParams: cmtproto.ConsensusParams{
Block: &cmtproto.BlockParams{
MaxBytes: 5 * 1024 * 1024,
MaxGas: -1,
},
Evidence: &cmtproto.EvidenceParams{
MaxAgeNumBlocks: 100,
MaxAgeDuration: time.Hour,
MaxBytes: 1024 * 1024,
},
Validator: &cmtproto.ValidatorParams{
PubKeyTypes: []string{cmttypes.ABCIPubKeyTypeEd25519},
},
},
}
}
// Export satisfies the server/types.AppExporter function type.
//
// e tracks relevant arguments under the e.Called struct.
//
// Export panics if neither e.ExportApp nor e.Err have been set.
func (e *mockExporter) Export(
logger log.Logger,
db dbm.DB,
traceWriter io.Writer,
height int64,
forZeroHeight bool,
jailAllowedAddrs []string,
opts types.AppOptions,
modulesToExport []string,
) (types.ExportedApp, error) {
if e.Err == nil && isZeroExportedApp(e.ExportApp) {
panic(fmt.Errorf("(*mockExporter).Export called without setting e.ExportApp or e.Err"))
}
e.WasCalled = true
e.Called.Height = height
e.Called.ForZeroHeight = forZeroHeight
e.Called.JailAllowedAddrs = jailAllowedAddrs
e.Called.ModulesToExport = modulesToExport
return e.ExportApp, e.Err
}
func TestExportCLI(t *testing.T) {
// Use t.Parallel in all of the subtests,
// because they all read from disk and risk blocking on io.
t.Run("fail on missing genesis file", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
sys := NewExportSystem(t, e.Export)
res := sys.Run("export")
require.Error(t, res.Err)
require.Truef(t, os.IsNotExist(res.Err), "expected resulting error to be os.IsNotExist, got %T (%v)", res.Err, res.Err)
require.False(t, e.WasCalled)
})
t.Run("prints to stdout by default", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
res := sys.MustRun(t, "export")
require.Empty(t, res.Stderr.String())
CheckExportedGenesis(t, res.Stdout.Bytes())
})
t.Run("passes expected default values to the AppExporter", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
_ = sys.MustRun(t, "export")
require.True(t, e.WasCalled)
require.Equal(t, int64(-1), e.Called.Height)
require.False(t, e.Called.ForZeroHeight)
require.Empty(t, e.Called.JailAllowedAddrs)
require.Empty(t, e.Called.ModulesToExport)
})
t.Run("passes flag values to the AppExporter", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
_ = sys.MustRun(t, "export",
"--height=100",
"--jail-allowed-addrs", "addr1,addr2",
"--modules-to-export", "foo,bar",
)
require.True(t, e.WasCalled)
require.Equal(t, int64(100), e.Called.Height)
require.False(t, e.Called.ForZeroHeight)
require.Equal(t, []string{"addr1", "addr2"}, e.Called.JailAllowedAddrs)
require.Equal(t, []string{"foo", "bar"}, e.Called.ModulesToExport)
})
t.Run("passes --for-zero-height to the AppExporter", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
_ = sys.MustRun(t, "export", "--for-zero-height")
require.True(t, e.WasCalled)
require.Equal(t, int64(-1), e.Called.Height)
require.True(t, e.Called.ForZeroHeight)
require.Empty(t, e.Called.JailAllowedAddrs)
require.Empty(t, e.Called.ModulesToExport)
})
t.Run("prints to a given file with --output-document", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
outDir := t.TempDir()
outFile := filepath.Join(outDir, "export.json")
res := sys.MustRun(t, "export", "--output-document", outFile)
require.Empty(t, res.Stderr.String())
require.Empty(t, res.Stdout.String())
j, err := os.ReadFile(outFile)
require.NoError(t, err)
CheckExportedGenesis(t, j)
})
t.Run("prints genesis to stdout when no app exporter defined", func(t *testing.T) {
t.Parallel()
sys := NewExportSystem(t, nil)
_ = sys.MustRun(t, "init", "some_moniker")
res := sys.MustRun(t, "export")
require.Contains(t, res.Stderr.String(), "WARNING: App exporter not defined.")
origGenesis, err := os.ReadFile(filepath.Join(sys.HomeDir, "config", "genesis.json"))
require.NoError(t, err)
out := res.Stdout.Bytes()
require.Equal(t, origGenesis, out)
})
t.Run("returns app exporter error", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.Err = fmt.Errorf("whoopsie")
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
res := sys.Run("export")
require.ErrorIs(t, res.Err, e.Err)
})
t.Run("rejects positional arguments", func(t *testing.T) {
t.Parallel()
e := new(mockExporter)
e.SetDefaultExportApp()
sys := NewExportSystem(t, e.Export)
_ = sys.MustRun(t, "init", "some_moniker")
outDir := t.TempDir()
outFile := filepath.Join(outDir, "export.json")
res := sys.Run("export", outFile)
require.Error(t, res.Err)
require.NoFileExists(t, outFile)
})
}
// CheckExportedGenesis fails t if j cannot be unmarshaled into a valid AppGenesis.
func CheckExportedGenesis(t *testing.T, j []byte) {
t.Helper()
var ag genutiltypes.AppGenesis
require.NoError(t, json.Unmarshal(j, &ag))
require.NotEmpty(t, ag.AppName)
require.NotZero(t, ag.GenesisTime)
require.NotEmpty(t, ag.ChainID)
require.NotNil(t, ag.Consensus)
}