forked from cosmos/cosmos-sdk
-
Notifications
You must be signed in to change notification settings - Fork 1
/
app_test.go
359 lines (319 loc) · 12.1 KB
/
app_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
package simapp
import (
"encoding/json"
"fmt"
"testing"
abci "github.com/cometbft/cometbft/abci/types"
cmtproto "github.com/cometbft/cometbft/proto/tendermint/types"
dbm "github.com/cosmos/cosmos-db"
"github.com/cosmos/gogoproto/proto"
"github.com/golang/mock/gomock"
"github.com/stretchr/testify/require"
"cosmossdk.io/core/address"
"cosmossdk.io/core/appmodule"
"cosmossdk.io/depinject"
"cosmossdk.io/log"
"cosmossdk.io/x/accounts"
"cosmossdk.io/x/auth"
"cosmossdk.io/x/auth/vesting"
authzmodule "cosmossdk.io/x/authz/module"
"cosmossdk.io/x/bank"
banktypes "cosmossdk.io/x/bank/types"
"cosmossdk.io/x/distribution"
"cosmossdk.io/x/epochs"
"cosmossdk.io/x/evidence"
feegrantmodule "cosmossdk.io/x/feegrant/module"
"cosmossdk.io/x/gov"
group "cosmossdk.io/x/group/module"
"cosmossdk.io/x/mint"
"cosmossdk.io/x/protocolpool"
"cosmossdk.io/x/slashing"
"cosmossdk.io/x/staking"
"cosmossdk.io/x/upgrade"
"github.com/cosmos/cosmos-sdk/baseapp"
"github.com/cosmos/cosmos-sdk/testutil/mock"
"github.com/cosmos/cosmos-sdk/testutil/network"
simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/cosmos/cosmos-sdk/types/module"
"github.com/cosmos/cosmos-sdk/types/msgservice"
"github.com/cosmos/cosmos-sdk/x/genutil"
)
func TestSimAppExportAndBlockedAddrs(t *testing.T) {
db := dbm.NewMemDB()
logger := log.NewTestLogger(t)
app := NewSimappWithCustomOptions(t, false, SetupOptions{
Logger: logger.With("instance", "first"),
DB: db,
AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
})
// BlockedAddresses returns a map of addresses in app v1 and a map of modules name in app v2.
for acc := range BlockedAddresses() {
var addr sdk.AccAddress
if modAddr, err := sdk.AccAddressFromBech32(acc); err == nil {
addr = modAddr
} else {
addr = app.AuthKeeper.GetModuleAddress(acc)
}
require.True(
t,
app.BankKeeper.BlockedAddr(addr),
fmt.Sprintf("ensure that blocked addresses are properly set in bank keeper: %s should be blocked", acc),
)
}
// finalize block so we have CheckTx state set
_, err := app.FinalizeBlock(&abci.RequestFinalizeBlock{
Height: 1,
})
require.NoError(t, err)
_, err = app.Commit()
require.NoError(t, err)
// Making a new app object with the db, so that initchain hasn't been called
app2 := NewSimApp(logger.With("instance", "second"), db, nil, true, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()))
_, err = app2.ExportAppStateAndValidators(false, []string{}, []string{})
require.NoError(t, err, "ExportAppStateAndValidators should not have an error")
}
func TestRunMigrations(t *testing.T) {
db := dbm.NewMemDB()
logger := log.NewTestLogger(t)
app := NewSimApp(logger.With("instance", "simapp"), db, nil, true, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()))
// Create a new baseapp and configurator for the purpose of this test.
bApp := baseapp.NewBaseApp(app.Name(), logger.With("instance", "baseapp"), db, app.TxConfig().TxDecoder())
bApp.SetCommitMultiStoreTracer(nil)
bApp.SetInterfaceRegistry(app.InterfaceRegistry())
app.BaseApp = bApp
configurator := module.NewConfigurator(app.appCodec, bApp.MsgServiceRouter(), app.GRPCQueryRouter())
// We register all modules on the Configurator, except x/bank. x/bank will
// serve as the test subject on which we run the migration tests.
//
// The loop below is the same as calling `RegisterServices` on
// ModuleManager, except that we skip x/bank.
for name, mod := range app.ModuleManager.Modules {
if name == banktypes.ModuleName {
continue
}
if mod, ok := mod.(module.HasServices); ok {
mod.RegisterServices(configurator)
}
if mod, ok := mod.(appmodule.HasServices); ok {
err := mod.RegisterServices(configurator)
require.NoError(t, err)
}
require.NoError(t, configurator.Error())
}
// Initialize the chain
_, err := app.InitChain(&abci.RequestInitChain{})
require.NoError(t, err)
_, err = app.Commit()
require.NoError(t, err)
testCases := []struct {
name string
moduleName string
fromVersion uint64
toVersion uint64
expRegErr bool // errors while registering migration
expRegErrMsg string
expRunErr bool // errors while running migration
expRunErrMsg string
expCalled int
}{
{
"cannot register migration for version 0",
"bank", 0, 1,
true, "module migration versions should start at 1: invalid version", false, "", 0,
},
{
"throws error on RunMigrations if no migration registered for bank",
"", 1, 2,
false, "", true, "no migrations found for module bank: not found", 0,
},
{
"can register 1->2 migration handler for x/bank, cannot run migration",
"bank", 1, 2,
false, "", true, "no migration found for module bank from version 2 to version 3: not found", 0,
},
{
"can register 2->3 migration handler for x/bank, can run migration",
"bank", 2, bank.AppModule{}.ConsensusVersion(),
false, "", false, "", int(bank.AppModule{}.ConsensusVersion() - 2), // minus 2 because 1-2 is run in the previous test case.
},
{
"cannot register migration handler for same module & fromVersion",
"bank", 1, 2,
true, "another migration for module bank and version 1 already exists: internal logic error", false, "", 0,
},
}
for _, tc := range testCases {
t.Run(tc.name, func(tt *testing.T) {
var err error
// Since it's very hard to test actual in-place store migrations in
// tests (due to the difficulty of maintaining multiple versions of a
// module), we're just testing here that the migration logic is
// called.
called := 0
if tc.moduleName != "" {
for i := tc.fromVersion; i < tc.toVersion; i++ {
// Register migration for module from version `fromVersion` to `fromVersion+1`.
tt.Logf("Registering migration for %q v%d", tc.moduleName, i)
err = configurator.RegisterMigration(tc.moduleName, i, func(sdk.Context) error {
called++
return nil
})
if tc.expRegErr {
require.EqualError(tt, err, tc.expRegErrMsg)
return
}
require.NoError(tt, err, "registering migration")
}
}
// Run migrations only for bank. That's why we put the initial
// version for bank as 1, and for all other modules, we put as
// their latest ConsensusVersion.
_, err = app.ModuleManager.RunMigrations(
app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()}), configurator,
module.VersionMap{
"accounts": accounts.AppModule{}.ConsensusVersion(),
"bank": 1,
"auth": auth.AppModule{}.ConsensusVersion(),
"authz": authzmodule.AppModule{}.ConsensusVersion(),
"staking": staking.AppModule{}.ConsensusVersion(),
"mint": mint.AppModule{}.ConsensusVersion(),
"distribution": distribution.AppModule{}.ConsensusVersion(),
"slashing": slashing.AppModule{}.ConsensusVersion(),
"gov": gov.AppModule{}.ConsensusVersion(),
"group": group.AppModule{}.ConsensusVersion(),
"upgrade": upgrade.AppModule{}.ConsensusVersion(),
"vesting": vesting.AppModule{}.ConsensusVersion(),
"feegrant": feegrantmodule.AppModule{}.ConsensusVersion(),
"evidence": evidence.AppModule{}.ConsensusVersion(),
"genutil": genutil.AppModule{}.ConsensusVersion(),
"protocolpool": protocolpool.AppModule{}.ConsensusVersion(),
"epochs": epochs.AppModule{}.ConsensusVersion(),
},
)
if tc.expRunErr {
require.EqualError(tt, err, tc.expRunErrMsg, "running migration")
} else {
require.NoError(tt, err, "running migration")
// Make sure bank's migration is called.
require.Equal(tt, tc.expCalled, called)
}
})
}
}
func TestInitGenesisOnMigration(t *testing.T) {
db := dbm.NewMemDB()
app := NewSimApp(log.NewTestLogger(t), db, nil, true, simtestutil.NewAppOptionsWithFlagHome(t.TempDir()))
ctx := app.NewContextLegacy(true, cmtproto.Header{Height: app.LastBlockHeight()})
// Create a mock module. This module will serve as the new module we're
// adding during a migration.
mockCtrl := gomock.NewController(t)
t.Cleanup(mockCtrl.Finish)
mockModule := mock.NewMockAppModuleWithAllExtensions(mockCtrl)
mockDefaultGenesis := json.RawMessage(`{"key": "value"}`)
mockModule.EXPECT().DefaultGenesis().Times(1).Return(mockDefaultGenesis)
mockModule.EXPECT().InitGenesis(gomock.Eq(ctx), gomock.Eq(mockDefaultGenesis)).Times(1)
mockModule.EXPECT().ConsensusVersion().Times(1).Return(uint64(0))
app.ModuleManager.Modules["mock"] = mockModule
// Run migrations only for "mock" module. We exclude it from
// the VersionMap to simulate upgrading with a new module.
_, err := app.ModuleManager.RunMigrations(ctx, app.Configurator(),
module.VersionMap{
"bank": bank.AppModule{}.ConsensusVersion(),
"auth": auth.AppModule{}.ConsensusVersion(),
"authz": authzmodule.AppModule{}.ConsensusVersion(),
"staking": staking.AppModule{}.ConsensusVersion(),
"mint": mint.AppModule{}.ConsensusVersion(),
"distribution": distribution.AppModule{}.ConsensusVersion(),
"slashing": slashing.AppModule{}.ConsensusVersion(),
"gov": gov.AppModule{}.ConsensusVersion(),
"upgrade": upgrade.AppModule{}.ConsensusVersion(),
"vesting": vesting.AppModule{}.ConsensusVersion(),
"feegrant": feegrantmodule.AppModule{}.ConsensusVersion(),
"evidence": evidence.AppModule{}.ConsensusVersion(),
"genutil": genutil.AppModule{}.ConsensusVersion(),
},
)
require.NoError(t, err)
}
func TestUpgradeStateOnGenesis(t *testing.T) {
db := dbm.NewMemDB()
app := NewSimappWithCustomOptions(t, false, SetupOptions{
Logger: log.NewTestLogger(t),
DB: db,
AppOpts: simtestutil.NewAppOptionsWithFlagHome(t.TempDir()),
})
// make sure the upgrade keeper has version map in state
ctx := app.NewContext(false)
vm, err := app.UpgradeKeeper.GetModuleVersionMap(ctx)
require.NoError(t, err)
for v, i := range app.ModuleManager.Modules {
if i, ok := i.(appmodule.HasConsensusVersion); ok {
require.Equal(t, vm[v], i.ConsensusVersion())
}
}
}
// TestMergedRegistry tests that fetching the gogo/protov2 merged registry
// doesn't fail after loading all file descriptors.
func TestMergedRegistry(t *testing.T) {
r, err := proto.MergedRegistry()
require.NoError(t, err)
require.Greater(t, r.NumFiles(), 0)
}
func TestProtoAnnotations(t *testing.T) {
r, err := proto.MergedRegistry()
require.NoError(t, err)
err = msgservice.ValidateProtoAnnotations(r)
require.NoError(t, err)
}
var _ address.Codec = (*customAddressCodec)(nil)
type customAddressCodec struct{}
func (c customAddressCodec) StringToBytes(text string) ([]byte, error) {
return []byte(text), nil
}
func (c customAddressCodec) BytesToString(bz []byte) (string, error) {
return string(bz), nil
}
func TestAddressCodecFactory(t *testing.T) {
var addrCodec address.Codec
var valAddressCodec address.ValidatorAddressCodec
var consAddressCodec address.ConsensusAddressCodec
err := depinject.Inject(
depinject.Configs(
network.MinimumAppConfig(),
depinject.Supply(log.NewNopLogger()),
),
&addrCodec, &valAddressCodec, &consAddressCodec)
require.NoError(t, err)
require.NotNil(t, addrCodec)
_, ok := addrCodec.(customAddressCodec)
require.False(t, ok)
require.NotNil(t, valAddressCodec)
_, ok = valAddressCodec.(customAddressCodec)
require.False(t, ok)
require.NotNil(t, consAddressCodec)
_, ok = consAddressCodec.(customAddressCodec)
require.False(t, ok)
// Set the address codec to the custom one
err = depinject.Inject(
depinject.Configs(
network.MinimumAppConfig(),
depinject.Supply(
log.NewNopLogger(),
func() address.Codec { return customAddressCodec{} },
func() address.ValidatorAddressCodec { return customAddressCodec{} },
func() address.ConsensusAddressCodec { return customAddressCodec{} },
),
),
&addrCodec, &valAddressCodec, &consAddressCodec)
require.NoError(t, err)
require.NotNil(t, addrCodec)
_, ok = addrCodec.(customAddressCodec)
require.True(t, ok)
require.NotNil(t, valAddressCodec)
_, ok = valAddressCodec.(customAddressCodec)
require.True(t, ok)
require.NotNil(t, consAddressCodec)
_, ok = consAddressCodec.(customAddressCodec)
require.True(t, ok)
}