From ebf53d377ac573c79bb52bc0521679f6d690c14f Mon Sep 17 00:00:00 2001 From: satawatnack Date: Tue, 19 Sep 2023 13:58:02 +0700 Subject: [PATCH] init refactor testdata --- benchmark/app_test.go | 12 +- benchmark/helper_test.go | 7 +- testing/{ => ibctesting}/chain.go | 31 +- testing/{ => ibctesting}/config.go | 0 testing/{ => ibctesting}/coordinator.go | 0 testing/{ => ibctesting}/endpoint.go | 0 testing/{ => ibctesting}/events.go | 0 testing/{ => ibctesting}/path.go | 0 testing/{ => ibctesting}/value.go | 0 testing/{testapp/setup.go => test_helpers.go} | 478 ++++++----- .../{testapp => testdata}/wasm_1_simple.go | 2 +- .../wasm_2_return_in_prepare.go | 2 +- .../wasm_3_do_nothing.go | 2 +- .../{testapp => testdata}/wasm_4_complex.go | 2 +- .../wasm_56_computation.go | 2 +- .../wasm_78_large_calldata.go | 2 +- .../wasm_9_set_data_several_times.go | 2 +- testing/{testapp => testdata}/wasm_extras.go | 6 +- testing/{testapp => testdata}/wasm_util.go | 13 +- testing/{testapp => }/util.go | 2 +- x/globalfee/feechecker/feechecker_test.go | 63 +- x/oracle/abci_test.go | 48 +- x/oracle/app_test.go | 51 +- x/oracle/handler_test.go | 373 +++++---- x/oracle/ibc_test.go | 158 ++-- x/oracle/keeper/data_source_test.go | 100 ++- x/oracle/keeper/grpc_query_test.go | 118 +-- x/oracle/keeper/keeper_test.go | 34 +- x/oracle/keeper/oracle_script_test.go | 63 +- x/oracle/keeper/owasm_test.go | 772 ++++++++++-------- x/oracle/keeper/params_test.go | 6 +- x/oracle/keeper/report_test.go | 104 ++- x/oracle/keeper/request_test.go | 88 +- x/oracle/keeper/result_test.go | 36 +- .../keeper/snapshotter_integration_test.go | 10 +- x/oracle/keeper/validator_status_test.go | 123 +-- 36 files changed, 1511 insertions(+), 1199 deletions(-) rename testing/{ => ibctesting}/chain.go (96%) rename testing/{ => ibctesting}/config.go (100%) rename testing/{ => ibctesting}/coordinator.go (100%) rename testing/{ => ibctesting}/endpoint.go (100%) rename testing/{ => ibctesting}/events.go (100%) rename testing/{ => ibctesting}/path.go (100%) rename testing/{ => ibctesting}/value.go (100%) rename testing/{testapp/setup.go => test_helpers.go} (82%) rename testing/{testapp => testdata}/wasm_1_simple.go (98%) rename testing/{testapp => testdata}/wasm_2_return_in_prepare.go (96%) rename testing/{testapp => testdata}/wasm_3_do_nothing.go (97%) rename testing/{testapp => testdata}/wasm_4_complex.go (99%) rename testing/{testapp => testdata}/wasm_56_computation.go (98%) rename testing/{testapp => testdata}/wasm_78_large_calldata.go (98%) rename testing/{testapp => testdata}/wasm_9_set_data_several_times.go (97%) rename testing/{testapp => testdata}/wasm_extras.go (89%) rename testing/{testapp => testdata}/wasm_util.go (74%) rename testing/{testapp => }/util.go (99%) diff --git a/benchmark/app_test.go b/benchmark/app_test.go index 312e2f7dc..9b4bf9dfa 100644 --- a/benchmark/app_test.go +++ b/benchmark/app_test.go @@ -4,19 +4,18 @@ import ( "testing" abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" "github.com/cosmos/cosmos-sdk/client" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - testapp "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" ) type BenchmarkApp struct { - *testapp.TestingApp + *bandtesting.TestingApp Sender *Account Validator *Account Oid uint64 @@ -29,15 +28,16 @@ type BenchmarkApp struct { } func InitializeBenchmarkApp(b testing.TB, maxGasPerBlock int64) *BenchmarkApp { + app, _ := bandtesting.CreateTestApp(&testing.T{}, false) ba := &BenchmarkApp{ - TestingApp: testapp.NewTestApp("", log.NewNopLogger()), + TestingApp: app, Sender: &Account{ - Account: testapp.Owner, + Account: bandtesting.Owner, Num: 0, Seq: 0, }, Validator: &Account{ - Account: testapp.Validators[0], + Account: bandtesting.Validators[0], Num: 5, Seq: 0, }, diff --git a/benchmark/helper_test.go b/benchmark/helper_test.go index 8b74a042b..f7c0a22bc 100644 --- a/benchmark/helper_test.go +++ b/benchmark/helper_test.go @@ -9,7 +9,8 @@ import ( "time" "github.com/bandprotocol/chain/v2/pkg/obi" - "github.com/bandprotocol/chain/v2/testing/testapp" + + bandtesting "github.com/bandprotocol/chain/v2/testing" oracletypes "github.com/bandprotocol/chain/v2/x/oracle/types" owasm "github.com/bandprotocol/go-owasm/api" types "github.com/cometbft/cometbft/abci/types" @@ -22,7 +23,7 @@ import ( ) type Account struct { - testapp.Account + bandtesting.Account Num uint64 Seq uint64 } @@ -127,7 +128,7 @@ func GenSequenceOfTxs( txs := make([]sdk.Tx, numTxs) for i := 0; i < numTxs; i++ { - txs[i], _ = testapp.GenTx( + txs[i], _ = bandtesting.GenTx( txConfig, msgs, sdk.Coins{sdk.NewInt64Coin("uband", 1)}, diff --git a/testing/chain.go b/testing/ibctesting/chain.go similarity index 96% rename from testing/chain.go rename to testing/ibctesting/chain.go index 78cdd9d00..368e3e49e 100644 --- a/testing/chain.go +++ b/testing/ibctesting/chain.go @@ -1,6 +1,7 @@ -// 0.47 TODO: consider importing directly from ibc instead of forking package ibctesting +// 0.47 TODO: consider importing directly from ibc instead of forking + import ( "bytes" "fmt" @@ -35,7 +36,7 @@ import ( "github.com/stretchr/testify/require" bandapp "github.com/bandprotocol/chain/v2/app" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -52,7 +53,7 @@ type TestChain struct { t *testing.T Coordinator *Coordinator - App *testapp.TestingApp + App *bandtesting.TestingApp ChainID string LastHeader *ibctmtypes.Header // header for last block height committed CurrentHeader tmproto.Header // header for current block height @@ -88,8 +89,8 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { for i := uint64(0); i < valSize; i++ { // generate validator private/public key - privVal := mock.PV{PrivKey: testapp.Validators[i].PrivKey} - tmPub, err := cryptocodec.ToTmPubKeyInterface(testapp.Validators[i].PubKey) + privVal := mock.PV{PrivKey: bandtesting.Validators[i].PrivKey} + tmPub, err := cryptocodec.ToTmPubKeyInterface(bandtesting.Validators[i].PubKey) require.NoError(t, err) // create validator set with two validators @@ -97,13 +98,13 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { signers[i] = privVal - senders[testapp.Validators[i].Address.String()] = authtypes.NewBaseAccount( - testapp.Validators[i].PubKey.Address().Bytes(), - testapp.Validators[i].PubKey, + senders[bandtesting.Validators[i].Address.String()] = authtypes.NewBaseAccount( + bandtesting.Validators[i].PubKey.Address().Bytes(), + bandtesting.Validators[i].PubKey, i, 0, ) - genesisAccount[i] = senders[testapp.Validators[i].Address.String()] + genesisAccount[i] = senders[bandtesting.Validators[i].Address.String()] balances[i] = banktypes.Balance{ Address: genesisAccount[i].GetAddress().String(), Coins: sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(10000000))), @@ -112,7 +113,7 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { valSet := tmtypes.NewValidatorSet(validators) - app := testapp.SetupWithGenesisValSet(t, valSet, genesisAccount, chainID, balances...) + app := bandtesting.SetupWithGenesisValSet(t, valSet, genesisAccount, chainID, balances...) ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) vals := app.StakingKeeper.GetAllValidators(ctx) for _, v := range vals { @@ -140,9 +141,9 @@ func NewTestChain(t *testing.T, coord *Coordinator, chainID string) *TestChain { Codec: app.AppCodec(), Vals: valSet, Signers: signers, - SenderPrivKey: testapp.Validators[0].PrivKey, + SenderPrivKey: bandtesting.Validators[0].PrivKey, SenderAccount: genesisAccount[0], - Treasury: testapp.Treasury.Address, + Treasury: bandtesting.Treasury.Address, senders: senders, } @@ -258,7 +259,7 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { // ensure the chain has the latest time chain.Coordinator.UpdateTimeForChain(chain) - _, r, err := testapp.SignAndDeliver( + _, r, err := bandtesting.SignAndDeliver( chain.t, chain.TxConfig, chain.App.GetBaseApp(), @@ -290,14 +291,14 @@ func (chain *TestChain) SendMsgs(msgs ...sdk.Msg) (*sdk.Result, error) { func (chain *TestChain) SendReport( rid types.RequestID, rawReps []types.RawReport, - sender testapp.Account, + sender bandtesting.Account, ) (*sdk.Result, error) { senderAccount := chain.senders[sender.Address.String()] // ensure the chain has the latest time chain.Coordinator.UpdateTimeForChain(chain) - _, r, err := testapp.SignAndDeliver( + _, r, err := bandtesting.SignAndDeliver( chain.t, chain.TxConfig, chain.App.GetBaseApp(), diff --git a/testing/config.go b/testing/ibctesting/config.go similarity index 100% rename from testing/config.go rename to testing/ibctesting/config.go diff --git a/testing/coordinator.go b/testing/ibctesting/coordinator.go similarity index 100% rename from testing/coordinator.go rename to testing/ibctesting/coordinator.go diff --git a/testing/endpoint.go b/testing/ibctesting/endpoint.go similarity index 100% rename from testing/endpoint.go rename to testing/ibctesting/endpoint.go diff --git a/testing/events.go b/testing/ibctesting/events.go similarity index 100% rename from testing/events.go rename to testing/ibctesting/events.go diff --git a/testing/path.go b/testing/ibctesting/path.go similarity index 100% rename from testing/path.go rename to testing/ibctesting/path.go diff --git a/testing/value.go b/testing/ibctesting/value.go similarity index 100% rename from testing/value.go rename to testing/ibctesting/value.go diff --git a/testing/testapp/setup.go b/testing/test_helpers.go similarity index 82% rename from testing/testapp/setup.go rename to testing/test_helpers.go index 9811dd0db..b7f33771f 100644 --- a/testing/testapp/setup.go +++ b/testing/test_helpers.go @@ -1,4 +1,4 @@ -package testapp +package testing import ( "encoding/json" @@ -10,6 +10,11 @@ import ( "testing" "time" + dbm "github.com/cometbft/cometbft-db" + abci "github.com/cometbft/cometbft/abci/types" + "github.com/cometbft/cometbft/libs/log" + tmproto "github.com/cometbft/cometbft/proto/tendermint/types" + tmtypes "github.com/cometbft/cometbft/types" "github.com/cosmos/cosmos-sdk/baseapp" "github.com/cosmos/cosmos-sdk/client" "github.com/cosmos/cosmos-sdk/client/flags" @@ -31,20 +36,14 @@ import ( slashingtypes "github.com/cosmos/cosmos-sdk/x/slashing/types" stakingkeeper "github.com/cosmos/cosmos-sdk/x/staking/keeper" stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - dbm "github.com/cometbft/cometbft-db" - abci "github.com/cometbft/cometbft/abci/types" - "github.com/cometbft/cometbft/libs/log" - tmproto "github.com/cometbft/cometbft/proto/tendermint/types" - tmtypes "github.com/cometbft/cometbft/types" ibckeeper "github.com/cosmos/ibc-go/v7/modules/core/keeper" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/pkg/filecache" owasm "github.com/bandprotocol/go-owasm/api" bandapp "github.com/bandprotocol/chain/v2/app" - "github.com/bandprotocol/chain/v2/x/oracle/keeper" + "github.com/bandprotocol/chain/v2/pkg/filecache" + "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -80,6 +79,7 @@ var ( Coins99999999uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 99999999)) Coins100000000uband = sdk.NewCoins(sdk.NewInt64Coin("uband", 100000000)) BadCoins = []sdk.Coin{{Denom: "uband", Amount: sdk.NewInt(-1)}} + ChainID = "BANDCHAIN" Port1 = "port-1" Port2 = "port-2" Channel1 = "channel-1" @@ -89,26 +89,9 @@ var ( const ( TestDefaultPrepareGas uint64 = 40000 TestDefaultExecuteGas uint64 = 300000 + DefaultGenTxGas = 1000000 ) -// DefaultConsensusParams defines the default Tendermint consensus params used in TestingApp. -var DefaultConsensusParams = &tmproto.ConsensusParams{ - Block: &tmproto.BlockParams{ - MaxBytes: 200000, - MaxGas: -1, - }, - Evidence: &tmproto.EvidenceParams{ - MaxAgeNumBlocks: 302400, - MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration - // MaxBytes: 10000, - }, - Validator: &tmproto.ValidatorParams{ - PubKeyTypes: []string{ - tmtypes.ABCIPubKeyTypeSecp256k1, - }, - }, -} - type TestingApp struct { *bandapp.BandApp } @@ -137,8 +120,25 @@ func (app *TestingApp) GetTxConfig() client.TxConfig { return bandapp.MakeEncodingConfig().TxConfig } +// DefaultConsensusParams defines the default Tendermint consensus params used in TestingApp. +var DefaultConsensusParams = &tmproto.ConsensusParams{ + Block: &tmproto.BlockParams{ + MaxBytes: 200000, + MaxGas: -1, + }, + Evidence: &tmproto.EvidenceParams{ + MaxAgeNumBlocks: 302400, + MaxAgeDuration: 504 * time.Hour, // 3 weeks is the max duration + // MaxBytes: 10000, + }, + Validator: &tmproto.ValidatorParams{ + PubKeyTypes: []string{ + tmtypes.ABCIPubKeyTypeSecp256k1, + }, + }, +} + func init() { - bandapp.SetBech32AddressPrefixesAndBip44CoinTypeAndSeal(sdk.GetConfig()) r := rand.New(rand.NewSource(time.Now().Unix())) Owner = createArbitraryAccount(r) Treasury = createArbitraryAccount(r) @@ -162,100 +162,25 @@ func init() { OwasmVM = owasmVM } -func createArbitraryAccount(r *rand.Rand) Account { - privkeySeed := make([]byte, 12) - r.Read(privkeySeed) - privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed) - return Account{ - PrivKey: privKey, - PubKey: privKey.PubKey(), - Address: sdk.AccAddress(privKey.PubKey().Address()), - ValAddress: sdk.ValAddress(privKey.PubKey().Address()), - } -} +// CreateTestApp creates a new test environment for unit tests. +func CreateTestApp(t *testing.T, autoActivate bool) (*TestingApp, sdk.Context) { + t.Helper() -func getGenesisDataSources(homePath string) []types.DataSource { - dir := filepath.Join(homePath, "files") - fc := filecache.New(dir) - DataSources = []types.DataSource{{}} // 0th index should be ignored - for idx := 0; idx < 5; idx++ { - idxStr := fmt.Sprintf("%d", idx+1) - hash := fc.AddFile([]byte("code" + idxStr)) - DataSources = append(DataSources, types.NewDataSource( - Owner.Address, "name"+idxStr, "desc"+idxStr, hash, Coins1000000uband, Treasury.Address, - )) - } - return DataSources[1:] -} + isCheckTx := false + app := Setup(t, ChainID) -func getGenesisOracleScripts(homePath string) []types.OracleScript { - dir := filepath.Join(homePath, "files") - fc := filecache.New(dir) - OracleScripts = []types.OracleScript{{}} // 0th index should be ignored - wasms := [][]byte{ - Wasm1, Wasm2, Wasm3, Wasm4, Wasm56(10), Wasm56(10000000), Wasm78(10), Wasm78(2000), Wasm9, - } - for idx := 0; idx < len(wasms); idx++ { - idxStr := fmt.Sprintf("%d", idx+1) - hash := fc.AddFile(compile(wasms[idx])) - OracleScripts = append(OracleScripts, types.NewOracleScript( - Owner.Address, "name"+idxStr, "desc"+idxStr, hash, "schema"+idxStr, "url"+idxStr, - )) + ctx := app.NewContext(isCheckTx, tmproto.Header{Height: app.LastBlockHeight()}) + if autoActivate { + app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) + app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) + app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) } - return OracleScripts[1:] -} - -// EmptyAppOptions is a stub implementing AppOptions -type EmptyAppOptions struct{} - -// Get implements AppOptions -func (ao EmptyAppOptions) Get(o string) interface{} { - return nil + return &TestingApp{app}, ctx } -// NewTestApp creates instance of our app using in test. -func NewTestApp(chainID string, logger log.Logger) *TestingApp { - // Set HomeFlag to a temp folder for simulation run. - dir, err := os.MkdirTemp("", "bandd") - if err != nil { - panic(err) - } - // db := dbm.NewMemDB() - db, _ := dbm.NewGoLevelDB("db", dir) - - appOptions := make(simtestutil.AppOptionsMap, 0) - appOptions[flags.FlagHome] = dir - appOptions[server.FlagInvCheckPeriod] = 0 +func Setup(t *testing.T, chainID string) *bandapp.BandApp { + t.Helper() - snapshotDir := filepath.Join(dir, "data", "snapshots") - snapshotDB, err := dbm.NewDB("metadata", dbm.GoLevelDBBackend, snapshotDir) - if err != nil { - panic(err) - } - snapshotStore, err := snapshots.NewStore(snapshotDB, snapshotDir) - if err != nil { - panic(err) - } - - snapshotOptions := snapshottypes.NewSnapshotOptions( - 1000, - 2, - ) - - app := &TestingApp{ - BandApp: bandapp.NewBandApp( - log.NewNopLogger(), - db, - nil, - true, - map[int64]bool{}, - appOptions, - 100, - baseapp.SetSnapshot(snapshotStore, snapshotOptions), - baseapp.SetChainID(chainID), - ), - } - genesis := bandapp.NewDefaultGenesisState() acc := []authtypes.GenesisAccount{ &authtypes.BaseAccount{Address: Owner.Address.String()}, &authtypes.BaseAccount{Address: FeePayer.Address.String()}, @@ -266,64 +191,6 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { &authtypes.BaseAccount{Address: Validators[1].Address.String()}, &authtypes.BaseAccount{Address: Validators[2].Address.String()}, } - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), acc) - genesis[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(Validators)) - signingInfos := make([]slashingtypes.SigningInfo, 0, len(Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(Validators)) - bamt := []sdk.Int{Coins100000000uband[0].Amount, Coins1000000uband[0].Amount, Coins99999999uband[0].Amount} - // bondAmt := sdk.NewInt(1000000) - for idx, val := range Validators { - tmpk, err := cryptocodec.ToTmPubKeyInterface(val.PubKey) - if err != nil { - panic(err) - } - pk, err := cryptocodec.FromTmPubKeyInterface(tmpk) - if err != nil { - panic(err) - } - pkAny, err := codectypes.NewAnyWithValue(pk) - if err != nil { - panic(err) - } - validator := stakingtypes.Validator{ - OperatorAddress: sdk.ValAddress(val.Address).String(), - ConsensusPubkey: pkAny, - Jailed: false, - Status: stakingtypes.Bonded, - Tokens: bamt[idx], - DelegatorShares: sdk.OneDec(), - Description: stakingtypes.Description{}, - UnbondingHeight: int64(0), - UnbondingTime: time.Unix(0, 0).UTC(), - Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), - MinSelfDelegation: sdk.ZeroInt(), - } - consAddr, err := validator.GetConsAddr() - validatorSigningInfo := slashingtypes.NewValidatorSigningInfo(consAddr, 0, 0, time.Unix(0, 0), false, 0) - if err != nil { - panic(err) - } - validators = append(validators, validator) - signingInfos = append( - signingInfos, - slashingtypes.SigningInfo{Address: consAddr.String(), ValidatorSigningInfo: validatorSigningInfo}, - ) - delegations = append( - delegations, - stakingtypes.NewDelegation(acc[4+idx].GetAddress(), val.Address.Bytes(), sdk.OneDec()), - ) - } - // set validators and delegations - stakingParams := stakingtypes.DefaultParams() - stakingParams.BondDenom = "uband" - stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) - genesis[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - slashingParams := slashingtypes.DefaultParams() - slashingGenesis := slashingtypes.NewGenesisState(slashingParams, signingInfos, nil) - genesis[slashingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(slashingGenesis) // Fund seed accounts and validators with 1000000uband and 100000000uband initially. balances := []banktypes.Balance{ @@ -339,38 +206,29 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { {Address: Validators[1].Address.String(), Coins: Coins100000000uband}, {Address: Validators[2].Address.String(), Coins: Coins100000000uband}, } - totalSupply := sdk.NewCoins() - for idx := 0; idx < len(balances)-len(validators); idx++ { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add(balances[idx].Coins...) - } - for idx := 0; idx < len(validators); idx++ { - // add genesis acc tokens and delegated tokens to total supply - totalSupply = totalSupply.Add( - balances[idx+len(balances)-len(validators)].Coins.Add(sdk.NewCoin("uband", bamt[idx]))...) - } - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin("uband", sdk.NewInt(200999999))}, - }) + app := setupWithGenesis(t, Validators, acc, chainID, balances...) - bankGenesis := banktypes.NewGenesisState( - banktypes.DefaultGenesisState().Params, - balances, - totalSupply, - []banktypes.Metadata{}, - []banktypes.SendEnabled{}, - ) - genesis[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + return app +} - // Add genesis data sources and oracle scripts - oracleGenesis := types.DefaultGenesisState() - oracleGenesis.DataSources = getGenesisDataSources(dir) - oracleGenesis.OracleScripts = getGenesisOracleScripts(dir) - genesis[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) - stateBytes, err := json.MarshalIndent(genesis, "", " ") +// SetupWithGenesisValSet initializes a new BandApp with a validator set and genesis accounts +// that also act as delegators. For simplicity, each validator is bonded with a delegation +// of one consensus engine unit in the default token of the JunoApp from first genesis +// account. +func setupWithGenesis( + t *testing.T, + valSet []Account, + genAccs []authtypes.GenesisAccount, + chainID string, + balances ...banktypes.Balance, +) *bandapp.BandApp { + t.Helper() + + app, genesisState, dir := setup(t, chainID, true) + genesisState = generateGenesisState(t, app, dir, genesisState, valSet, genAccs, balances...) + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") if err != nil { panic(err) } @@ -385,24 +243,15 @@ func NewTestApp(chainID string, logger log.Logger) *TestingApp { return app } -// CreateTestInput creates a new test environment for unit tests. -func CreateTestInput(autoActivate bool) (*TestingApp, sdk.Context, keeper.Keeper) { - app := NewTestApp("BANDCHAIN", log.NewNopLogger()) - ctx := app.NewContext(false, tmproto.Header{Height: app.LastBlockHeight()}) - if autoActivate { - app.OracleKeeper.Activate(ctx, Validators[0].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[1].ValAddress) - app.OracleKeeper.Activate(ctx, Validators[2].ValAddress) - } - return app, ctx, app.OracleKeeper -} +func setup(t *testing.T, chainID string, withGenesis bool) (*bandapp.BandApp, bandapp.GenesisState, string) { + t.Helper() -func setup(withGenesis bool, invCheckPeriod uint, chainID string) (*TestingApp, bandapp.GenesisState, string) { - dir, err := os.MkdirTemp("", "bandibc") + // Set HomeFlag to a temp folder for simulation run. + dir, err := os.MkdirTemp("", "bandd") if err != nil { panic(err) } - db := dbm.NewMemDB() + db, _ := dbm.NewGoLevelDB("db", dir) appOptions := make(simtestutil.AppOptionsMap, 0) appOptions[flags.FlagHome] = dir @@ -423,28 +272,29 @@ func setup(withGenesis bool, invCheckPeriod uint, chainID string) (*TestingApp, 2, ) - app := &TestingApp{ - BandApp: bandapp.NewBandApp( - log.NewNopLogger(), - db, - nil, - true, - map[int64]bool{}, - appOptions, - 0, - baseapp.SetSnapshot(snapshotStore, snapshotOptions), - baseapp.SetChainID(chainID), - ), - } + app := bandapp.NewBandApp( + log.NewNopLogger(), + db, + nil, + true, + map[int64]bool{}, + appOptions, + 100, + baseapp.SetSnapshot(snapshotStore, snapshotOptions), + baseapp.SetChainID(chainID), + ) if withGenesis { return app, bandapp.NewDefaultGenesisState(), dir } - return app, bandapp.GenesisState{}, dir + + return app, bandapp.GenesisState{}, "" } -// SetupWithEmptyStore setup a TestingApp instance with empty DB -func SetupWithEmptyStore() *TestingApp { - app, _, _ := setup(false, 0, "BANDCHAIN") +// SetupWithEmptyStore setup a instance with empty DB +func SetupWithEmptyStore(t *testing.T, chainID string) *bandapp.BandApp { + t.Helper() + + app, _, _ := setup(t, chainID, false) return app } @@ -459,7 +309,10 @@ func SetupWithGenesisValSet( chainID string, balances ...banktypes.Balance, ) *TestingApp { - app, genesisState, dir := setup(true, 5, chainID) + t.Helper() + + app, genesisState, dir := setup(t, chainID, true) + // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) @@ -524,8 +377,8 @@ func SetupWithGenesisValSet( // Add genesis data sources and oracle scripts oracleGenesis := types.DefaultGenesisState() - oracleGenesis.DataSources = getGenesisDataSources(dir) - oracleGenesis.OracleScripts = getGenesisOracleScripts(dir) + oracleGenesis.DataSources = generateDataSources(dir) + oracleGenesis.OracleScripts = generateOracleScripts(dir) genesisState[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) stateBytes, err := json.MarshalIndent(genesisState, "", " ") @@ -551,12 +404,155 @@ func SetupWithGenesisValSet( NextValidatorsHash: valSet.Hash(), }, Hash: app.LastCommitID().Hash}) - return app + return &TestingApp{app} } -const ( - DefaultGenTxGas = 1000000 -) +func createArbitraryAccount(r *rand.Rand) Account { + privkeySeed := make([]byte, 12) + r.Read(privkeySeed) + privKey := secp256k1.GenPrivKeyFromSecret(privkeySeed) + return Account{ + PrivKey: privKey, + PubKey: privKey.PubKey(), + Address: sdk.AccAddress(privKey.PubKey().Address()), + ValAddress: sdk.ValAddress(privKey.PubKey().Address()), + } +} + +func generateGenesisState( + t *testing.T, + app *bandapp.BandApp, + dir string, + genesisState bandapp.GenesisState, + valSet []Account, + genAccs []authtypes.GenesisAccount, + balances ...banktypes.Balance, +) bandapp.GenesisState { + t.Helper() + + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) + + validators := make([]stakingtypes.Validator, 0, len(valSet)) + signingInfos := make([]slashingtypes.SigningInfo, 0, len(valSet)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet)) + bamt := []sdk.Int{Coins100000000uband[0].Amount, Coins1000000uband[0].Amount, Coins99999999uband[0].Amount} + for idx, val := range valSet { + tmpk, err := cryptocodec.ToTmPubKeyInterface(val.PubKey) + if err != nil { + panic(err) + } + pk, err := cryptocodec.FromTmPubKeyInterface(tmpk) + if err != nil { + panic(err) + } + pkAny, err := codectypes.NewAnyWithValue(pk) + if err != nil { + panic(err) + } + validator := stakingtypes.Validator{ + OperatorAddress: sdk.ValAddress(val.Address).String(), + ConsensusPubkey: pkAny, + Jailed: false, + Status: stakingtypes.Bonded, + Tokens: bamt[idx], + DelegatorShares: sdk.OneDec(), + Description: stakingtypes.Description{}, + UnbondingHeight: int64(0), + UnbondingTime: time.Unix(0, 0).UTC(), + Commission: stakingtypes.NewCommission(sdk.ZeroDec(), sdk.ZeroDec(), sdk.ZeroDec()), + MinSelfDelegation: sdk.ZeroInt(), + } + consAddr, err := validator.GetConsAddr() + validatorSigningInfo := slashingtypes.NewValidatorSigningInfo(consAddr, 0, 0, time.Unix(0, 0), false, 0) + if err != nil { + panic(err) + } + validators = append(validators, validator) + signingInfos = append( + signingInfos, + slashingtypes.SigningInfo{Address: consAddr.String(), ValidatorSigningInfo: validatorSigningInfo}, + ) + delegations = append( + delegations, + stakingtypes.NewDelegation(genAccs[4+idx].GetAddress(), val.Address.Bytes(), sdk.OneDec()), + ) + } + // set validators and delegations + stakingParams := stakingtypes.DefaultParams() + stakingParams.BondDenom = "uband" + stakingGenesis := stakingtypes.NewGenesisState(stakingParams, validators, delegations) + genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) + + slashingParams := slashingtypes.DefaultParams() + slashingGenesis := slashingtypes.NewGenesisState(slashingParams, signingInfos, nil) + genesisState[slashingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(slashingGenesis) + + totalSupply := sdk.NewCoins() + for idx := 0; idx < len(balances)-len(validators); idx++ { + // add genesis acc tokens and delegated tokens to total supply + totalSupply = totalSupply.Add(balances[idx].Coins...) + } + for idx := 0; idx < len(validators); idx++ { + // add genesis acc tokens and delegated tokens to total supply + totalSupply = totalSupply.Add( + balances[idx+len(balances)-len(validators)].Coins.Add(sdk.NewCoin("uband", bamt[idx]))...) + } + + // add bonded amount to bonded pool module account + balances = append(balances, banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: sdk.Coins{sdk.NewCoin("uband", sdk.NewInt(200999999))}, + }) + + bankGenesis := banktypes.NewGenesisState( + banktypes.DefaultGenesisState().Params, + balances, + totalSupply, + []banktypes.Metadata{}, + []banktypes.SendEnabled{}, + ) + genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + + // Add genesis data sources and oracle scripts + oracleGenesis := types.DefaultGenesisState() + oracleGenesis.DataSources = generateDataSources(dir) + oracleGenesis.OracleScripts = generateOracleScripts(dir) + genesisState[types.ModuleName] = app.AppCodec().MustMarshalJSON(oracleGenesis) + + return genesisState +} + +func generateDataSources(homePath string) []types.DataSource { + dir := filepath.Join(homePath, "files") + fc := filecache.New(dir) + DataSources = []types.DataSource{{}} // 0th index should be ignored + for idx := 0; idx < 5; idx++ { + idxStr := fmt.Sprintf("%d", idx+1) + hash := fc.AddFile([]byte("code" + idxStr)) + DataSources = append(DataSources, types.NewDataSource( + Owner.Address, "name"+idxStr, "desc"+idxStr, hash, Coins1000000uband, Treasury.Address, + )) + } + return DataSources[1:] +} + +func generateOracleScripts(homePath string) []types.OracleScript { + dir := filepath.Join(homePath, "files") + fc := filecache.New(dir) + OracleScripts = []types.OracleScript{{}} // 0th index should be ignored + wasms := [][]byte{ + testdata.Wasm1, testdata.Wasm2, testdata.Wasm3, testdata.Wasm4, testdata.Wasm56(10), testdata.Wasm56(10000000), testdata.Wasm78(10), testdata.Wasm78(2000), testdata.Wasm9, + } + for idx := 0; idx < len(wasms); idx++ { + idxStr := fmt.Sprintf("%d", idx+1) + hash := fc.AddFile(testdata.Compile(wasms[idx])) + OracleScripts = append(OracleScripts, types.NewOracleScript( + Owner.Address, "name"+idxStr, "desc"+idxStr, hash, "schema"+idxStr, "url"+idxStr, + )) + } + return OracleScripts[1:] +} // GenTx generates a signed mock transaction. func GenTx( diff --git a/testing/testapp/wasm_1_simple.go b/testing/testdata/wasm_1_simple.go similarity index 98% rename from testing/testapp/wasm_1_simple.go rename to testing/testdata/wasm_1_simple.go index c7e822917..e6a4829f2 100644 --- a/testing/testapp/wasm_1_simple.go +++ b/testing/testdata/wasm_1_simple.go @@ -1,4 +1,4 @@ -package testapp +package testdata // A simple Owasm script with the following specification: // diff --git a/testing/testapp/wasm_2_return_in_prepare.go b/testing/testdata/wasm_2_return_in_prepare.go similarity index 96% rename from testing/testapp/wasm_2_return_in_prepare.go rename to testing/testdata/wasm_2_return_in_prepare.go index 96f736e51..4814fbd59 100644 --- a/testing/testapp/wasm_2_return_in_prepare.go +++ b/testing/testdata/wasm_2_return_in_prepare.go @@ -1,4 +1,4 @@ -package testapp +package testdata // A bad Owasm script with the following specification: // diff --git a/testing/testapp/wasm_3_do_nothing.go b/testing/testdata/wasm_3_do_nothing.go similarity index 97% rename from testing/testapp/wasm_3_do_nothing.go rename to testing/testdata/wasm_3_do_nothing.go index 43f9ca30f..39d03c327 100644 --- a/testing/testapp/wasm_3_do_nothing.go +++ b/testing/testdata/wasm_3_do_nothing.go @@ -1,4 +1,4 @@ -package testapp +package testdata // A silly oracle script, primarily to test that you must make at least one raw request: // diff --git a/testing/testapp/wasm_4_complex.go b/testing/testdata/wasm_4_complex.go similarity index 99% rename from testing/testapp/wasm_4_complex.go rename to testing/testdata/wasm_4_complex.go index 8320036e1..680df10b9 100644 --- a/testing/testapp/wasm_4_complex.go +++ b/testing/testdata/wasm_4_complex.go @@ -1,4 +1,4 @@ -package testapp +package testdata import ( "encoding/hex" diff --git a/testing/testapp/wasm_56_computation.go b/testing/testdata/wasm_56_computation.go similarity index 98% rename from testing/testapp/wasm_56_computation.go rename to testing/testdata/wasm_56_computation.go index b00cd5185..fbd06538e 100644 --- a/testing/testapp/wasm_56_computation.go +++ b/testing/testdata/wasm_56_computation.go @@ -1,4 +1,4 @@ -package testapp +package testdata import ( "fmt" diff --git a/testing/testapp/wasm_78_large_calldata.go b/testing/testdata/wasm_78_large_calldata.go similarity index 98% rename from testing/testapp/wasm_78_large_calldata.go rename to testing/testdata/wasm_78_large_calldata.go index 012dfa121..95736ffb8 100644 --- a/testing/testapp/wasm_78_large_calldata.go +++ b/testing/testdata/wasm_78_large_calldata.go @@ -1,4 +1,4 @@ -package testapp +package testdata import ( "fmt" diff --git a/testing/testapp/wasm_9_set_data_several_times.go b/testing/testdata/wasm_9_set_data_several_times.go similarity index 97% rename from testing/testapp/wasm_9_set_data_several_times.go rename to testing/testdata/wasm_9_set_data_several_times.go index f235f2117..8f7d9f3dc 100644 --- a/testing/testapp/wasm_9_set_data_several_times.go +++ b/testing/testdata/wasm_9_set_data_several_times.go @@ -1,4 +1,4 @@ -package testapp +package testdata var Wasm9 []byte = wat2wasm([]byte(` (module diff --git a/testing/testapp/wasm_extras.go b/testing/testdata/wasm_extras.go similarity index 89% rename from testing/testapp/wasm_extras.go rename to testing/testdata/wasm_extras.go index 7de803843..bca7a2599 100644 --- a/testing/testapp/wasm_extras.go +++ b/testing/testdata/wasm_extras.go @@ -1,4 +1,4 @@ -package testapp +package testdata import ( "crypto/sha256" @@ -34,8 +34,8 @@ var WasmExtra1FileName string var WasmExtra2FileName string func init() { - wasm1CompiledHash := sha256.Sum256(compile(WasmExtra1)) - wasm2CompiledHash := sha256.Sum256(compile(WasmExtra2)) + wasm1CompiledHash := sha256.Sum256(Compile(WasmExtra1)) + wasm2CompiledHash := sha256.Sum256(Compile(WasmExtra2)) WasmExtra1FileName = hex.EncodeToString(wasm1CompiledHash[:]) WasmExtra2FileName = hex.EncodeToString(wasm2CompiledHash[:]) } diff --git a/testing/testapp/wasm_util.go b/testing/testdata/wasm_util.go similarity index 74% rename from testing/testapp/wasm_util.go rename to testing/testdata/wasm_util.go index f894b967d..cc3c62153 100644 --- a/testing/testapp/wasm_util.go +++ b/testing/testdata/wasm_util.go @@ -1,14 +1,21 @@ -package testapp +package testdata import ( "os" "os/exec" + owasm "github.com/bandprotocol/go-owasm/api" + "github.com/bandprotocol/chain/v2/x/oracle/types" ) -func compile(code []byte) []byte { - compiled, err := OwasmVM.Compile(code, types.MaxCompiledWasmCodeSize) +func Compile(code []byte) []byte { + owasmVM, err := owasm.NewVm(10) + if err != nil { + panic(err) + } + + compiled, err := owasmVM.Compile(code, types.MaxCompiledWasmCodeSize) if err != nil { panic(err) } diff --git a/testing/testapp/util.go b/testing/util.go similarity index 99% rename from testing/testapp/util.go rename to testing/util.go index e45ffc483..e6b928297 100644 --- a/testing/testapp/util.go +++ b/testing/util.go @@ -1,4 +1,4 @@ -package testapp +package testing import ( "fmt" diff --git a/x/globalfee/feechecker/feechecker_test.go b/x/globalfee/feechecker/feechecker_test.go index b525670b1..afb7995e4 100644 --- a/x/globalfee/feechecker/feechecker_test.go +++ b/x/globalfee/feechecker/feechecker_test.go @@ -8,7 +8,7 @@ import ( "github.com/cosmos/cosmos-sdk/x/authz" "github.com/stretchr/testify/suite" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/globalfee/feechecker" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -58,36 +58,39 @@ type FeeCheckerTestSuite struct { } func (suite *FeeCheckerTestSuite) SetupTest() { - app, ctx, oracleKeeper := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + suite.ctx = ctx.WithBlockHeight(999). WithIsCheckTx(true). WithMinGasPrices(sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(1, 4)}}) - oracleKeeper.GrantReporter(suite.ctx, testapp.Validators[0].ValAddress, testapp.Alice.Address) + app.OracleKeeper.GrantReporter(suite.ctx, bandtesting.Validators[0].ValAddress, bandtesting.Alice.Address) req := types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", nil, nil, 0, ) - suite.requestId = oracleKeeper.AddRequest(suite.ctx, req) + suite.requestId = app.OracleKeeper.AddRequest(suite.ctx, req) suite.FeeChecker = feechecker.NewFeeChecker( - &oracleKeeper, + &app.OracleKeeper, &app.GlobalfeeKeeper, app.StakingKeeper, ) } func (suite *FeeCheckerTestSuite) TestValidRawReport() { - msgs := []sdk.Msg{types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress)} + msgs := []sdk.Msg{ + types.NewMsgReportData(suite.requestId, []types.RawReport{}, bandtesting.Validators[0].ValAddress), + } stubTx := &StubTx{Msgs: msgs} // test - check report tx @@ -102,7 +105,7 @@ func (suite *FeeCheckerTestSuite) TestValidRawReport() { } func (suite *FeeCheckerTestSuite) TestNotValidRawReport() { - msgs := []sdk.Msg{types.NewMsgReportData(1, []types.RawReport{}, testapp.Alice.ValAddress)} + msgs := []sdk.Msg{types.NewMsgReportData(1, []types.RawReport{}, bandtesting.Alice.ValAddress)} stubTx := &StubTx{Msgs: msgs} // test - check report tx @@ -116,9 +119,9 @@ func (suite *FeeCheckerTestSuite) TestNotValidRawReport() { func (suite *FeeCheckerTestSuite) TestValidReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestId, []types.RawReport{}, bandtesting.Validators[0].ValAddress), } - authzMsg := authz.NewMsgExec(testapp.Alice.Address, reportMsgs) + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} // test - check report tx @@ -134,9 +137,9 @@ func (suite *FeeCheckerTestSuite) TestValidReport() { func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestId, []types.RawReport{}, bandtesting.Validators[0].ValAddress), } - authzMsg := authz.NewMsgExec(testapp.Bob.Address, reportMsgs) + authzMsg := authz.NewMsgExec(bandtesting.Bob.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}, GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1)))} // test - check report tx @@ -150,9 +153,9 @@ func (suite *FeeCheckerTestSuite) TestNoAuthzReport() { func (suite *FeeCheckerTestSuite) TestNotValidReport() { reportMsgs := []sdk.Msg{ - types.NewMsgReportData(suite.requestId+1, []types.RawReport{}, testapp.Validators[0].ValAddress), + types.NewMsgReportData(suite.requestId+1, []types.RawReport{}, bandtesting.Validators[0].ValAddress), } - authzMsg := authz.NewMsgExec(testapp.Alice.Address, reportMsgs) + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, reportMsgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}} // test - check report tx @@ -171,10 +174,10 @@ func (suite *FeeCheckerTestSuite) TestNotReportMsg() { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) stubTx := &StubTx{ Msgs: []sdk.Msg{requestMsg}, @@ -201,20 +204,20 @@ func (suite *FeeCheckerTestSuite) TestNotReportMsg() { } func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsgs() { - reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress) + reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, bandtesting.Validators[0].ValAddress) requestMsg := types.NewMsgRequestData( 1, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) msgs := []sdk.Msg{reportMsg, requestMsg} - authzMsg := authz.NewMsgExec(testapp.Alice.Address, msgs) + authzMsg := authz.NewMsgExec(bandtesting.Alice.Address, msgs) stubTx := &StubTx{Msgs: []sdk.Msg{&authzMsg}, GasPrices: sdk.NewDecCoins(sdk.NewDecCoin("uband", sdk.NewInt(1)))} // test - check report tx @@ -229,17 +232,17 @@ func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameAuthzMsg } func (suite *FeeCheckerTestSuite) TestReportMsgAndOthersTypeMsgInTheSameTx() { - reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, testapp.Validators[0].ValAddress) + reportMsg := types.NewMsgReportData(suite.requestId, []types.RawReport{}, bandtesting.Validators[0].ValAddress) requestMsg := types.NewMsgRequestData( 1, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) stubTx := &StubTx{ Msgs: []sdk.Msg{reportMsg, requestMsg}, diff --git a/x/oracle/abci_test.go b/x/oracle/abci_test.go index 37c6dfa7a..7bcfda68a 100644 --- a/x/oracle/abci_test.go +++ b/x/oracle/abci_test.go @@ -11,7 +11,7 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" ) func fromHex(hexStr string) []byte { @@ -23,7 +23,9 @@ func fromHex(hexStr string) []byte { } func TestRollingSeedCorrect(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + // Initially rolling seed should be all zeros. require.Equal( t, @@ -58,12 +60,14 @@ func TestRollingSeedCorrect(t *testing.T) { } func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + votes := []abci.VoteInfo{{ - Validator: abci.Validator{Address: testapp.Validators[0].PubKey.Address(), Power: 70}, + Validator: abci.Validator{Address: bandtesting.Validators[0].PubKey.Address(), Power: 70}, SignedLastBlock: true, }, { - Validator: abci.Validator{Address: testapp.Validators[1].PubKey.Address(), Power: 30}, + Validator: abci.Validator{Address: bandtesting.Validators[1].PubKey.Address(), Power: 30}, SignedLastBlock: true, }} // Set collected fee to 100uband + 70% oracle reward proportion + disable minting inflation. @@ -102,7 +106,7 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress()), ) // 1 validator active, begin block should take 70% of the fee. 2% of that goes to comm pool. - k.Activate(ctx, testapp.Validators[1].ValAddress) + k.Activate(ctx, bandtesting.Validators[1].ValAddress) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -124,15 +128,15 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { app.DistrKeeper.GetFeePool(ctx).CommunityPool, ) // 0uband - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress)) // 100*70%*98% = 68.6uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(686, 1)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) // 2 validators active now. 70% of the remaining fee pool will be split 3 ways (comm pool + val1 + val2). - k.Activate(ctx, testapp.Validators[0].ValAddress) + k.Activate(ctx, bandtesting.Validators[0].ValAddress) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -157,16 +161,16 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(14406, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) // 68.6uband + 30*70%*98%*30% = 74.774uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(74774, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) // 1 validator becomes in active, and will not get reward this time. - k.MissReport(ctx, testapp.Validators[1].ValAddress, testapp.ParseTime(100)) + k.MissReport(ctx, bandtesting.Validators[1].ValAddress, bandtesting.ParseTime(100)) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -191,24 +195,26 @@ func TestAllocateTokensCalledOnBeginBlock(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(20286, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) // 74.774uband require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(74774, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) } func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + ctx = ctx.WithBlockHeight(10) // Set block height to ensure distr's AllocateTokens gets called. votes := []abci.VoteInfo{{ - Validator: abci.Validator{Address: testapp.Validators[0].PubKey.Address(), Power: 70}, + Validator: abci.Validator{Address: bandtesting.Validators[0].PubKey.Address(), Power: 70}, SignedLastBlock: true, }, { - Validator: abci.Validator{Address: testapp.Validators[1].PubKey.Address(), Power: 30}, + Validator: abci.Validator{Address: bandtesting.Validators[1].PubKey.Address(), Power: 30}, SignedLastBlock: true, }} @@ -232,7 +238,7 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { params.OracleRewardPercentage = 70 k.SetParams(ctx, params) // Set block proposer to Validators[1], who will receive 5% bonus. - app.DistrKeeper.SetPreviousProposerConsAddr(ctx, testapp.Validators[1].Address.Bytes()) + app.DistrKeeper.SetPreviousProposerConsAddr(ctx, bandtesting.Validators[1].Address.Bytes()) require.Equal( t, sdk.NewCoins(sdk.NewInt64Coin("uband", 50)), @@ -252,7 +258,7 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { // Community pool: 0.7 + 0.3 = 1 // Validators[0]: 34.3 + 8.715 = 43.015 // Validators[1]: 2.25 + 3.735 = 5.985 - k.Activate(ctx, testapp.Validators[0].ValAddress) + k.Activate(ctx, bandtesting.Validators[0].ValAddress) app.BeginBlocker(ctx, abci.RequestBeginBlock{ Hash: fromHex("ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff"), LastCommitInfo: abci.CommitInfo{Votes: votes}, @@ -271,11 +277,11 @@ func TestAllocateTokensWithDistrAllocateTokens(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(44590, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDecWithPrec(4410, 3)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) } diff --git a/x/oracle/app_test.go b/x/oracle/app_test.go index 25d364eee..06014da4c 100644 --- a/x/oracle/app_test.go +++ b/x/oracle/app_test.go @@ -9,13 +9,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestSuccessRequestOracleData(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper ctx = ctx.WithBlockHeight(4).WithBlockTime(time.Unix(1581589790, 0)) handler := oracle.NewHandler(k) @@ -26,12 +27,11 @@ func TestSuccessRequestOracleData(t *testing.T) { 2, "app_test", sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(9000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Validators[0].Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Validators[0].Address, ) res, err := handler(ctx, requestMsg) - fmt.Println(err) require.NotNil(t, res) require.NoError(t, err) @@ -39,13 +39,13 @@ func TestSuccessRequestOracleData(t *testing.T) { types.OracleScriptID(1), []byte("calldata"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 2, 4, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "app_test", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -53,7 +53,7 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, ) app.EndBlocker(ctx, abci.RequestEndBlock{Height: 4}) request, err := k.GetRequest(ctx, types.RequestID(1)) @@ -66,7 +66,7 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawReport(2, 0, []byte("answer2")), types.NewRawReport(3, 0, []byte("answer3")), }, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ) res, err = handler(ctx, reportMsg1) require.NotNil(t, res) @@ -89,7 +89,7 @@ func TestSuccessRequestOracleData(t *testing.T) { types.NewRawReport(2, 0, []byte("answer2")), types.NewRawReport(3, 0, []byte("answer3")), }, - testapp.Validators[1].ValAddress, + bandtesting.Validators[1].ValAddress, ) res, err = handler(ctx, reportMsg2) require.NotNil(t, res) @@ -126,7 +126,8 @@ func TestSuccessRequestOracleData(t *testing.T) { } func TestExpiredRequestOracleData(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper ctx = ctx.WithBlockHeight(4).WithBlockTime(time.Unix(1581589790, 0)) handler := oracle.NewHandler(k) @@ -137,9 +138,9 @@ func TestExpiredRequestOracleData(t *testing.T) { 2, "app_test", sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(9000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Validators[0].Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Validators[0].Address, ) res, err := handler(ctx, requestMsg) require.NotNil(t, res) @@ -149,13 +150,13 @@ func TestExpiredRequestOracleData(t *testing.T) { types.OracleScriptID(1), []byte("calldata"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 2, 4, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "app_test", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -163,7 +164,7 @@ func TestExpiredRequestOracleData(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, ) app.EndBlocker(ctx, abci.RequestEndBlock{Height: 4}) request, err := k.GetRequest(ctx, types.RequestID(1)) @@ -190,7 +191,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[2].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[2].ValAddress.String()), }, }, }, { @@ -198,7 +199,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[0].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[0].ValAddress.String()), }, }, }, { @@ -206,7 +207,7 @@ func TestExpiredRequestOracleData(t *testing.T) { Attributes: []abci.EventAttribute{ { Key: types.AttributeKeyValidator, - Value: fmt.Sprint(testapp.Validators[1].ValAddress.String()), + Value: fmt.Sprint(bandtesting.Validators[1].ValAddress.String()), }, }, }} diff --git a/x/oracle/handler_test.go b/x/oracle/handler_test.go index 8009d5a8d..712958994 100644 --- a/x/oracle/handler_test.go +++ b/x/oracle/handler_test.go @@ -17,16 +17,19 @@ import ( "github.com/bandprotocol/go-owasm/api" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestCreateDataSourceSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + dsCount := k.GetDataSourceCount(ctx) - treasury := testapp.Treasury.Address - owner := testapp.Owner.Address + treasury := bandtesting.Treasury.Address + owner := bandtesting.Owner.Address name := "data_source_1" description := "description" executable := []byte("executable") @@ -36,10 +39,10 @@ func TestCreateDataSourceSuccess(t *testing.T) { name, description, executable, - testapp.EmptyCoins, + bandtesting.EmptyCoins, treasury, owner, - testapp.Alice.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -47,7 +50,7 @@ func TestCreateDataSourceSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewDataSource(testapp.Owner.Address, name, description, filename, testapp.EmptyCoins, treasury), + types.NewDataSource(bandtesting.Owner.Address, name, description, filename, bandtesting.EmptyCoins, treasury), ds, ) event := abci.Event{ @@ -60,9 +63,11 @@ func TestCreateDataSourceSuccess(t *testing.T) { } func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - treasury := testapp.Treasury.Address - owner := testapp.Owner.Address + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + treasury := bandtesting.Treasury.Address + owner := bandtesting.Owner.Address name := "data_source_1" description := "description" executable := []byte("executable") @@ -70,12 +75,12 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { zw := gz.NewWriter(&buf) zw.Write(executable) zw.Close() - sender := testapp.Alice.Address + sender := bandtesting.Alice.Address msg := types.NewMsgCreateDataSource( name, description, buf.Bytes()[:5], - testapp.EmptyCoins, + bandtesting.EmptyCoins, treasury, owner, sender, @@ -86,7 +91,9 @@ func TestCreateGzippedExecutableDataSourceFail(t *testing.T) { } func TestEditDataSourceSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "beeb" newDescription := "new_description" newExecutable := []byte("executable2") @@ -97,10 +104,10 @@ func TestEditDataSourceSuccess(t *testing.T) { newName, newDescription, newExecutable, - testapp.Coins1000000uband, - testapp.Treasury.Address, - testapp.Alice.Address, - testapp.Owner.Address, + bandtesting.Coins1000000uband, + bandtesting.Treasury.Address, + bandtesting.Alice.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -109,12 +116,12 @@ func TestEditDataSourceSuccess(t *testing.T) { require.Equal( t, types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, newName, newDescription, newFilename, - testapp.Coins1000000uband, - testapp.Treasury.Address, + bandtesting.Coins1000000uband, + bandtesting.Treasury.Address, ), ds, ) @@ -126,7 +133,9 @@ func TestEditDataSourceSuccess(t *testing.T) { } func TestEditDataSourceFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "beeb" newDescription := "new_description" newExecutable := []byte("executable2") @@ -136,13 +145,13 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, newExecutable, - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrDataSourceNotFound, "id: 42") + bandtesting.CheckErrorf(t, err, types.ErrDataSourceNotFound, "id: 42") require.Nil(t, res) // Not owner msg = types.NewMsgEditDataSource( @@ -150,10 +159,10 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, newExecutable, - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Bob.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Bob.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrEditorNotAuthorized) @@ -168,10 +177,10 @@ func TestEditDataSourceFail(t *testing.T) { newName, newDescription, buf.Bytes()[:5], - testapp.EmptyCoins, - testapp.Treasury.Address, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -179,11 +188,13 @@ func TestEditDataSourceFail(t *testing.T) { } func TestCreateOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + osCount := k.GetOracleScriptCount(ctx) name := "os_1" description := "beeb" - code := testapp.WasmExtra1 + code := testdata.WasmExtra1 schema := "schema" url := "url" msg := types.NewMsgCreateOracleScript( @@ -192,8 +203,8 @@ func TestCreateOracleScriptSuccess(t *testing.T) { schema, url, code, - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -201,7 +212,14 @@ func TestCreateOracleScriptSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewOracleScript(testapp.Owner.Address, name, description, testapp.WasmExtra1FileName, schema, url), + types.NewOracleScript( + bandtesting.Owner.Address, + name, + description, + testdata.WasmExtra1FileName, + schema, + url, + ), os, ) @@ -215,7 +233,9 @@ func TestCreateOracleScriptSuccess(t *testing.T) { } func TestCreateGzippedOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + osCount := k.GetOracleScriptCount(ctx) name := "os_1" description := "beeb" @@ -223,7 +243,7 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { url := "url" var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + zw.Write(testdata.WasmExtra1) zw.Close() msg := types.NewMsgCreateOracleScript( name, @@ -231,8 +251,8 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { schema, url, buf.Bytes(), - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -240,7 +260,14 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { require.NoError(t, err) require.Equal( t, - types.NewOracleScript(testapp.Owner.Address, name, description, testapp.WasmExtra1FileName, schema, url), + types.NewOracleScript( + bandtesting.Owner.Address, + name, + description, + testdata.WasmExtra1FileName, + schema, + url, + ), os, ) @@ -254,7 +281,9 @@ func TestCreateGzippedOracleScriptSuccess(t *testing.T) { } func TestCreateOracleScriptFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + name := "os_1" description := "beeb" schema := "schema" @@ -266,16 +295,16 @@ func TestCreateOracleScriptFail(t *testing.T) { schema, url, []byte("BAD"), - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) + bandtesting.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) require.Nil(t, res) // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra1) + zw.Write(testdata.WasmExtra1) zw.Close() msg = types.NewMsgCreateOracleScript( name, @@ -283,8 +312,8 @@ func TestCreateOracleScriptFail(t *testing.T) { schema, url, buf.Bytes()[:5], - testapp.Owner.Address, - testapp.Alice.Address, + bandtesting.Owner.Address, + bandtesting.Alice.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -292,10 +321,12 @@ func TestCreateOracleScriptFail(t *testing.T) { } func TestEditOracleScriptSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "os_2" newDescription := "beebbeeb" - newCode := testapp.WasmExtra2 + newCode := testdata.WasmExtra2 newSchema := "new_schema" newURL := "new_url" msg := types.NewMsgEditOracleScript( @@ -305,8 +336,8 @@ func TestEditOracleScriptSuccess(t *testing.T) { newSchema, newURL, newCode, - testapp.Alice.Address, - testapp.Owner.Address, + bandtesting.Alice.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) @@ -315,10 +346,10 @@ func TestEditOracleScriptSuccess(t *testing.T) { require.Equal( t, types.NewOracleScript( - testapp.Alice.Address, + bandtesting.Alice.Address, newName, newDescription, - testapp.WasmExtra2FileName, + testdata.WasmExtra2FileName, newSchema, newURL, ), @@ -333,10 +364,12 @@ func TestEditOracleScriptSuccess(t *testing.T) { } func TestEditOracleScriptFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + newName := "os_2" newDescription := "beebbeeb" - newCode := testapp.WasmExtra2 + newCode := testdata.WasmExtra2 newSchema := "new_schema" newURL := "new_url" // Bad ID @@ -347,11 +380,11 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, newCode, - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") + bandtesting.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") require.Nil(t, res) // Not owner msg = types.NewMsgEditOracleScript( @@ -361,8 +394,8 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, newCode, - testapp.Owner.Address, - testapp.Bob.Address, + bandtesting.Owner.Address, + bandtesting.Bob.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.EqualError(t, err, "editor not authorized") @@ -375,16 +408,16 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, []byte("BAD_CODE"), - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) - testapp.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) + bandtesting.CheckErrorf(t, err, types.ErrOwasmCompilation, "caused by %s", api.ErrValidation) require.Nil(t, res) // Bad Gzip var buf bytes.Buffer zw := gz.NewWriter(&buf) - zw.Write(testapp.WasmExtra2) + zw.Write(testdata.WasmExtra2) zw.Close() msg = types.NewMsgEditOracleScript( 1, @@ -393,8 +426,8 @@ func TestEditOracleScriptFail(t *testing.T) { newSchema, newURL, buf.Bytes()[:5], - testapp.Owner.Address, - testapp.Owner.Address, + bandtesting.Owner.Address, + bandtesting.Owner.Address, ) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrUncompressionFailed) @@ -402,28 +435,30 @@ func TestEditOracleScriptFail(t *testing.T) { } func TestRequestDataSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockHeight(124).WithBlockTime(testapp.ParseTime(1581589790)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockHeight(124).WithBlockTime(bandtesting.ParseTime(1581589790)) msg := types.NewMsgRequestData( 1, []byte("beeb"), 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) require.Equal(t, types.NewRequest( 1, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[2].ValAddress, testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[2].ValAddress, bandtesting.Validators[0].ValAddress}, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -431,12 +466,12 @@ func TestRequestDataSuccess(t *testing.T) { types.NewRawRequest(3, 3, []byte("beeb")), }, nil, - uint64(testapp.TestDefaultExecuteGas), + uint64(bandtesting.TestDefaultExecuteGas), ), k.MustGetRequest(ctx, 1)) event := abci.Event{ Type: authtypes.EventTypeCoinSpent, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeySpender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeySpender, Value: bandtesting.FeePayer.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -446,7 +481,7 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: authtypes.EventTypeCoinReceived, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeyReceiver, Value: testapp.Treasury.Address.String()}, + {Key: authtypes.AttributeKeyReceiver, Value: bandtesting.Treasury.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -456,8 +491,8 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: authtypes.EventTypeTransfer, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeyRecipient, Value: testapp.Treasury.Address.String()}, - {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeyRecipient, Value: bandtesting.Treasury.Address.String()}, + {Key: authtypes.AttributeKeySender, Value: bandtesting.FeePayer.Address.String()}, {Key: sdk.AttributeKeyAmount, Value: "2000000uband"}, }, } @@ -467,7 +502,7 @@ func TestRequestDataSuccess(t *testing.T) { event = abci.Event{ Type: sdk.EventTypeMessage, Attributes: []abci.EventAttribute{ - {Key: authtypes.AttributeKeySender, Value: testapp.FeePayer.Address.String()}, + {Key: authtypes.AttributeKeySender, Value: bandtesting.FeePayer.Address.String()}, }, } require.Equal(t, abci.Event(event), res.Events[3]) @@ -485,8 +520,8 @@ func TestRequestDataSuccess(t *testing.T) { {Key: types.AttributeKeyMinCount, Value: "2"}, {Key: types.AttributeKeyGasUsed, Value: "5294700000"}, {Key: types.AttributeKeyTotalFees, Value: "6000000uband"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[2].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, abci.Event(event), res.Events[12]) @@ -494,7 +529,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "1"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[1].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[1].Filename}, {Key: types.AttributeKeyExternalID, Value: "1"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -505,7 +540,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "2"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[2].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[2].Filename}, {Key: types.AttributeKeyExternalID, Value: "2"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -516,7 +551,7 @@ func TestRequestDataSuccess(t *testing.T) { Type: types.EventTypeRawRequest, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyDataSourceID, Value: "3"}, - {Key: types.AttributeKeyDataSourceHash, Value: testapp.DataSources[3].Filename}, + {Key: types.AttributeKeyDataSourceHash, Value: bandtesting.DataSources[3].Filename}, {Key: types.AttributeKeyExternalID, Value: "3"}, {Key: types.AttributeKeyCalldata, Value: "beeb"}, {Key: types.AttributeKeyFee, Value: "1000000uband"}, @@ -526,7 +561,9 @@ func TestRequestDataSuccess(t *testing.T) { } func TestRequestDataFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + // No active oracle validators res, err := oracle.NewHandler( k, @@ -538,16 +575,16 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ), ) - testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") + bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "0 < 2") require.Nil(t, res) - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + k.Activate(ctx, bandtesting.Validators[0].ValAddress) + k.Activate(ctx, bandtesting.Validators[1].ValAddress) // Too large calldata res, err = oracle.NewHandler( k, @@ -559,13 +596,13 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ), ) - testapp.CheckErrorf(t, err, types.ErrTooLargeCalldata, "got: 8000, max: 512") + bandtesting.CheckErrorf(t, err, types.ErrTooLargeCalldata, "got: 8000, max: 512") require.Nil(t, res) // Too high ask count res, err = oracle.NewHandler( @@ -578,13 +615,13 @@ func TestRequestDataFail(t *testing.T) { 3, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ), ) - testapp.CheckErrorf(t, err, types.ErrInsufficientValidators, "2 < 3") + bandtesting.CheckErrorf(t, err, types.ErrInsufficientValidators, "2 < 3") require.Nil(t, res) // Bad oracle script ID res, err = oracle.NewHandler( @@ -597,13 +634,13 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ), ) - testapp.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") + bandtesting.CheckErrorf(t, err, types.ErrOracleScriptNotFound, "id: 999") require.Nil(t, res) // Pay not enough fee res, err = oracle.NewHandler( @@ -616,30 +653,32 @@ func TestRequestDataFail(t *testing.T) { 2, 2, "CID", - testapp.EmptyCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.EmptyCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ), ) - testapp.CheckErrorf(t, err, types.ErrNotEnoughFee, "require: 2000000uband, max: 0uband") + bandtesting.CheckErrorf(t, err, types.ErrNotEnoughFee, "require: 2000000uband, max: 0uband") require.Nil(t, res) } func TestReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Set up a mock request asking 3 validators with min count 2. k.SetRequest(ctx, 42, types.NewRequest( 1, []byte("beeb"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, - testapp.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, }, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -651,63 +690,65 @@ func TestReportSuccess(t *testing.T) { // Common raw reports for everyone. reports := []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte("data2"))} // Validators[0] reports data. - res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[0].ValAddress)) + res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[0].ValAddress)) require.NoError(t, err) require.Equal(t, []types.RequestID{}, k.GetPendingResolveList(ctx)) event := abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, abci.Event(event), res.Events[0]) // Validators[1] reports data. Now the request should move to pending resolve. - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[1].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[1].ValAddress)) require.NoError(t, err) require.Equal(t, []types.RequestID{42}, k.GetPendingResolveList(ctx)) event = abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[1].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[1].ValAddress.String()}, }, } require.Equal(t, abci.Event(event), res.Events[0]) // Even if we resolve the request, Validators[2] should still be able to report. k.SetPendingResolveList(ctx, []types.RequestID{}) k.ResolveSuccess(ctx, 42, []byte("RESOLVE_RESULT!"), 1234) - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[2].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[2].ValAddress)) require.NoError(t, err) event = abci.Event{ Type: types.EventTypeReport, Attributes: []abci.EventAttribute{ {Key: types.AttributeKeyID, Value: "42"}, - {Key: types.AttributeKeyValidator, Value: testapp.Validators[2].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[2].ValAddress.String()}, }, } require.Equal(t, abci.Event(event), res.Events[0]) // Check the reports of this request. We should see 3 reports, with report from Validators[2] comes after resolve. finalReport := k.GetReports(ctx, 42) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[0].ValAddress, true, reports)) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[1].ValAddress, true, reports)) - require.Contains(t, finalReport, types.NewReport(testapp.Validators[2].ValAddress, false, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[0].ValAddress, true, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[1].ValAddress, true, reports)) + require.Contains(t, finalReport, types.NewReport(bandtesting.Validators[2].ValAddress, false, reports)) } func TestReportFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Set up a mock request asking 3 validators with min count 2. k.SetRequest(ctx, 42, types.NewRequest( 1, []byte("beeb"), []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, - testapp.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, }, 2, 124, - testapp.ParseTime(1581589790), + bandtesting.ParseTime(1581589790), "CID", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -719,17 +760,17 @@ func TestReportFail(t *testing.T) { // Common raw reports for everyone. reports := []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte("data2"))} // Bad ID - res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(999, reports, testapp.Validators[0].ValAddress)) - testapp.CheckErrorf(t, err, types.ErrRequestNotFound, "id: 999") + res, err := oracle.NewHandler(k)(ctx, types.NewMsgReportData(999, reports, bandtesting.Validators[0].ValAddress)) + bandtesting.CheckErrorf(t, err, types.ErrRequestNotFound, "id: 999") require.Nil(t, res) // Not-asked validator - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Alice.ValAddress)) - testapp.CheckErrorf( + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Alice.ValAddress)) + bandtesting.CheckErrorf( t, err, types.ErrValidatorNotRequested, "reqID: 42, val: %s", - testapp.Alice.ValAddress.String(), + bandtesting.Alice.ValAddress.String(), ) require.Nil(t, res) // Too large report data size @@ -743,10 +784,10 @@ func TestReportFail(t *testing.T) { types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(2, 0, []byte(strings.Repeat("data2", 2000))), }, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) - testapp.CheckErrorf(t, err, types.ErrTooLargeRawReportData, "got: 10000, max: 512") + bandtesting.CheckErrorf(t, err, types.ErrTooLargeRawReportData, "got: 10000, max: 512") require.Nil(t, res) // Not having all raw reports res, err = oracle.NewHandler( @@ -756,7 +797,7 @@ func TestReportFail(t *testing.T) { types.NewMsgReportData( 42, []types.RawReport{types.NewRawReport(1, 0, []byte("data1"))}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) require.ErrorIs(t, err, types.ErrInvalidReportSize) @@ -769,63 +810,69 @@ func TestReportFail(t *testing.T) { types.NewMsgReportData( 42, []types.RawReport{types.NewRawReport(1, 0, []byte("data1")), types.NewRawReport(42, 0, []byte("data2"))}, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, ), ) - testapp.CheckErrorf(t, err, types.ErrRawRequestNotFound, "reqID: 42, extID: 42") + bandtesting.CheckErrorf(t, err, types.ErrRawRequestNotFound, "reqID: 42, extID: 42") require.Nil(t, res) // Request already expired k.SetRequestLastExpired(ctx, 42) - res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, testapp.Validators[0].ValAddress)) + res, err = oracle.NewHandler(k)(ctx, types.NewMsgReportData(42, reports, bandtesting.Validators[0].ValAddress)) require.ErrorIs(t, err, types.ErrRequestAlreadyExpired) require.Nil(t, res) } func TestActivateSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) - ctx = ctx.WithBlockTime(testapp.ParseTime(1000000)) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1000000)) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), - k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress), + k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress), ) - msg := types.NewMsgActivate(testapp.Validators[0].ValAddress) + msg := types.NewMsgActivate(bandtesting.Validators[0].ValAddress) res, err := oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) require.Equal(t, - types.NewValidatorStatus(true, testapp.ParseTime(1000000)), - k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress), + types.NewValidatorStatus(true, bandtesting.ParseTime(1000000)), + k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress), ) event := abci.Event{ Type: types.EventTypeActivate, Attributes: []abci.EventAttribute{ - {Key: types.AttributeKeyValidator, Value: testapp.Validators[0].ValAddress.String()}, + {Key: types.AttributeKeyValidator, Value: bandtesting.Validators[0].ValAddress.String()}, }, } require.Equal(t, abci.Event(event), res.Events[0]) } func TestActivateFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - msg := types.NewMsgActivate(testapp.Validators[0].ValAddress) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + msg := types.NewMsgActivate(bandtesting.Validators[0].ValAddress) // Already active. res, err := oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrValidatorAlreadyActive) require.Nil(t, res) // Too soon to activate. - ctx = ctx.WithBlockTime(testapp.ParseTime(100000)) - k.MissReport(ctx, testapp.Validators[0].ValAddress, testapp.ParseTime(99999)) - ctx = ctx.WithBlockTime(testapp.ParseTime(100001)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(100000)) + k.MissReport(ctx, bandtesting.Validators[0].ValAddress, bandtesting.ParseTime(99999)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(100001)) res, err = oracle.NewHandler(k)(ctx, msg) require.ErrorIs(t, err, types.ErrTooSoonToActivate) require.Nil(t, res) // OK - ctx = ctx.WithBlockTime(testapp.ParseTime(200000)) + ctx = ctx.WithBlockTime(bandtesting.ParseTime(200000)) _, err = oracle.NewHandler(k)(ctx, msg) require.NoError(t, err) } func TestUpdateParamsSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, @@ -878,7 +925,9 @@ func TestUpdateParamsSuccess(t *testing.T) { } func TestUpdateParamsFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, diff --git a/x/oracle/ibc_test.go b/x/oracle/ibc_test.go index d31f212f2..4d69175da 100644 --- a/x/oracle/ibc_test.go +++ b/x/oracle/ibc_test.go @@ -12,9 +12,9 @@ import ( "github.com/stretchr/testify/suite" "github.com/bandprotocol/chain/v2/pkg/obi" - - ibctesting "github.com/bandprotocol/chain/v2/testing" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/testing/ibctesting" + "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -86,8 +86,8 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { 2, 2, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(6000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -102,7 +102,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + suite.chainB.SendReport(1, raws1, bandtesting.Validators[0]) suite.Require().NoError(err) raws2 := []types.RawReport{ @@ -110,7 +110,7 @@ func (suite *OracleTestSuite) TestHandleIBCRequestSuccess() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + suite.chainB.SendReport(1, raws2, bandtesting.Validators[1]) suite.Require().NoError(err) oracleResponsePacket := types.NewOracleResponsePacketData( @@ -156,8 +156,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 1, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -166,8 +166,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 0, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( clientID, @@ -176,8 +176,8 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 2, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), types.NewOracleRequestPacketData( strings.Repeat(clientID, 9), @@ -186,11 +186,29 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { 1, 1, coins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + ), + types.NewOracleRequestPacketData( + clientID, + 1, + []byte("beeb"), + 1, + 1, + coins, + 0, + bandtesting.TestDefaultExecuteGas, + ), + types.NewOracleRequestPacketData( + clientID, + 1, + []byte("beeb"), + 1, + 1, + coins, + bandtesting.TestDefaultPrepareGas, + 0, ), - types.NewOracleRequestPacketData(clientID, 1, []byte("beeb"), 1, 1, coins, 0, testapp.TestDefaultExecuteGas), - types.NewOracleRequestPacketData(clientID, 1, []byte("beeb"), 1, 1, coins, testapp.TestDefaultPrepareGas, 0), types.NewOracleRequestPacketData( clientID, 1, @@ -207,9 +225,9 @@ func (suite *OracleTestSuite) TestIBCPrepareValidateBasicFail() { []byte("beeb"), 1, 1, - testapp.BadCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.BadCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ), } @@ -234,12 +252,12 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFund() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) // Use Carol as a relayer - carol := testapp.Carol + carol := bandtesting.Carol carolExpectedBalance := sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2492500))) suite.chainB.SendMsgs(banktypes.NewMsgSend( suite.chainB.SenderAccount.GetAddress(), @@ -274,8 +292,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughFeeLimit() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -297,8 +315,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidCalldataSize() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -318,7 +336,7 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestNotEnoughPrepareGas() { 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), 1, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -338,8 +356,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidAskCountFail() { 17, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -353,8 +371,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidAskCountFail() { 3, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet = suite.sendOracleRequestPacket(path, 2, oracleRequestPacket, timeoutHeight) @@ -379,8 +397,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBaseOwasmFeePanic() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -405,8 +423,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestPerValidatorRequestFeePanic() 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -427,8 +445,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestOracleScriptNotFound() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -448,8 +466,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestBadWasmExecutionFail() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -469,8 +487,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestWithEmptyRawRequest() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -490,8 +508,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestUnknownDataSource() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -511,15 +529,15 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestInvalidDataSourceCount() { oracleRequestPacket := types.NewOracleRequestPacketData( path.EndpointA.ClientID, 4, - obi.MustEncode(testapp.Wasm4Input{ + obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", }), 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(4000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -539,8 +557,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestTooMuchWasmGas() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -559,8 +577,8 @@ func (suite *OracleTestSuite) TestIBCPrepareRequestTooLargeCalldata() { 1, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -580,7 +598,7 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { 2, 1, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(6000000))), - testapp.TestDefaultPrepareGas, + bandtesting.TestDefaultPrepareGas, 1, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -596,7 +614,7 @@ func (suite *OracleTestSuite) TestIBCResolveRequestOutOfGas() { types.NewRawReport(2, 0, []byte("data2")), types.NewRawReport(3, 0, []byte("data3")), } - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -636,12 +654,12 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { oracleRequestPacket := types.NewOracleRequestPacketData( path.EndpointA.ClientID, 4, - obi.MustEncode(testapp.Wasm4Input{IDs: []int64{1, 2}, Calldata: string("beeb")}), + obi.MustEncode(testdata.Wasm4Input{IDs: []int64{1, 2}, Calldata: string("beeb")}), 2, 2, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(4000000))), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, ) packet := suite.sendOracleRequestPacket(path, 1, oracleRequestPacket, timeoutHeight) @@ -652,10 +670,10 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { suite.checkChainBSenderBalances(sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(5970000)))) raws1 := []types.RawReport{types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1"))} - suite.chainB.SendReport(1, raws1, testapp.Validators[0]) + suite.chainB.SendReport(1, raws1, bandtesting.Validators[0]) raws2 := []types.RawReport{types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil)} - suite.chainB.SendReport(1, raws2, testapp.Validators[1]) + suite.chainB.SendReport(1, raws2, bandtesting.Validators[1]) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -671,7 +689,7 @@ func (suite *OracleTestSuite) TestIBCResolveReadNilExternalData() { 1577923380, 1577923405, types.RESOLVE_STATUS_SUCCESS, - obi.MustEncode(testapp.Wasm4Output{Ret: "beebd1v2beebd2v1"}), + obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v2beebd2v1"}), ) responsePacket := channeltypes.NewPacket( oracleResponsePacket.GetBytes(), @@ -694,12 +712,12 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { // 3rd Wasm - do nothing 3, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), @@ -709,7 +727,7 @@ func (suite *OracleTestSuite) TestIBCResolveRequestNoReturnData() { )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -748,22 +766,22 @@ func (suite *OracleTestSuite) TestIBCResolveRequestWasmFailure() { // 6th Wasm - out-of-gas 6, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), @@ -802,22 +820,22 @@ func (suite *OracleTestSuite) TestIBCResolveRequestCallReturnDataSeveralTimes() // 9th Wasm - set return data several times 9, []byte("beeb"), - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, suite.chainB.GetContext(). BlockHeight()- 1, - testapp.ParseTime(1577923380), + bandtesting.ParseTime(1577923380), path.EndpointA.ClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), }, &types.IBCChannel{PortId: path.EndpointB.ChannelConfig.PortID, ChannelId: path.EndpointB.ChannelID}, - testapp.TestDefaultExecuteGas, + bandtesting.TestDefaultExecuteGas, )) raws := []types.RawReport{types.NewRawReport(1, 0, []byte("beeb"))} - suite.chainB.SendReport(1, raws, testapp.Validators[0]) + suite.chainB.SendReport(1, raws, bandtesting.Validators[0]) commitment := suite.chainB.App.IBCKeeper.ChannelKeeper.GetPacketCommitment( suite.chainB.GetContext(), diff --git a/x/oracle/keeper/data_source_test.go b/x/oracle/keeper/data_source_test.go index 5178327d1..278255182 100644 --- a/x/oracle/keeper/data_source_test.go +++ b/x/oracle/keeper/data_source_test.go @@ -1,48 +1,58 @@ package keeper_test import ( + "fmt" "testing" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestHasDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a data source ID 42 without setting it. require.False(t, k.HasDataSource(ctx, 42)) // After we set it, we should be able to find it. k.SetDataSource(ctx, 42, types.NewDataSource( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, testapp.EmptyCoins, testapp.Treasury.Address, + bandtesting.Owner.Address, + BasicName, + BasicDesc, + BasicFilename, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, )) require.True(t, k.HasDataSource(ctx, 42)) } func TestSetterGetterDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent data source should return error. _, err := k.GetDataSource(ctx, 42) require.ErrorIs(t, err, types.ErrDataSourceNotFound) require.Panics(t, func() { _ = k.MustGetDataSource(ctx, 42) }) // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "filename1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "filename2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Sets id 42 with data soure 1 and id 42 with data source 2. k.SetDataSource(ctx, 42, dataSource1) @@ -63,23 +73,25 @@ func TestSetterGetterDataSource(t *testing.T) { } func TestAddDataSourceEditDataSourceBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Adds a new data source to the store. We should be able to retrieve it back. id := k.AddDataSource(ctx, dataSource1) @@ -91,30 +103,32 @@ func TestAddDataSourceEditDataSourceBasic(t *testing.T) { require.NoError(t, err) // Edits the data source. We should get the updated data source. k.MustEditDataSource(ctx, id, types.NewDataSource( - owner, dataSource2.Name, dataSource2.Description, dataSource2.Filename, testapp.EmptyCoins, treasury, + owner, dataSource2.Name, dataSource2.Description, dataSource2.Filename, bandtesting.EmptyCoins, treasury, )) require.NotEqual(t, dataSource1, k.MustGetDataSource(ctx, id)) require.Equal(t, dataSource2, k.MustGetDataSource(ctx, id)) } func TestEditDataSourceDoNotModify(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic data sources. dataSource1 := types.NewDataSource( - testapp.Alice.Address, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) dataSource2 := types.NewDataSource( - testapp.Bob.Address, + bandtesting.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ) // Adds a new data source to the store. We should be able to retrieve it back. id := k.AddDataSource(ctx, dataSource1) @@ -134,20 +148,24 @@ func TestEditDataSourceDoNotModify(t *testing.T) { } func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially we expect the data source count to be what we have on genesis state. - genesisCount := uint64(len(testapp.DataSources)) - 1 + genesisCount := uint64(len(bandtesting.DataSources)) - 1 + fmt.Println(genesisCount, k.GetDataSourceCount(ctx)) require.Equal(t, genesisCount, k.GetDataSourceCount(ctx)) + // Every new data source we add should return a new ID. id1 := k.AddDataSource( ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ), ) require.Equal(t, types.DataSourceID(genesisCount+1), id1) @@ -155,12 +173,12 @@ func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { id2 := k.AddDataSource( ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, - testapp.EmptyCoins, - testapp.Treasury.Address, + bandtesting.EmptyCoins, + bandtesting.Treasury.Address, ), ) require.Equal(t, types.DataSourceID(genesisCount+2), id2) @@ -169,18 +187,24 @@ func TestAddDataSourceDataSourceMustReturnCorrectID(t *testing.T) { } func TestEditDataSourceNonExistentDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - require.Panics(t, func() { k.MustEditDataSource(ctx, 9999, testapp.DataSources[1]) }) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + require.Panics(t, func() { k.MustEditDataSource(ctx, 9999, bandtesting.DataSources[1]) }) } func TestGetAllDataSources(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should be able to get all genesis data sources. - require.Equal(t, testapp.DataSources[1:], k.GetAllDataSources(ctx)) + require.Equal(t, bandtesting.DataSources[1:], k.GetAllDataSources(ctx)) } func TestAddExecutableFile(t *testing.T) { - _, _, k := testapp.CreateTestInput(true) + app, _ := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Adding do-not-modify should simply return do-not-modify. require.Equal(t, types.DoNotModify, k.AddExecutableFile(types.DoNotModifyBytes)) // After we add an executable file, we should be able to retrieve it back. diff --git a/x/oracle/keeper/grpc_query_test.go b/x/oracle/keeper/grpc_query_test.go index 0ed02531f..f40eb6595 100644 --- a/x/oracle/keeper/grpc_query_test.go +++ b/x/oracle/keeper/grpc_query_test.go @@ -12,7 +12,7 @@ import ( "github.com/stretchr/testify/require" "github.com/stretchr/testify/suite" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -33,7 +33,8 @@ type RequestVerificationTestSuite struct { func (suite *RequestVerificationTestSuite) SetupTest() { suite.assert = require.New(suite.T()) - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + k := app.OracleKeeper suite.querier = keeper.Querier{ Keeper: k, @@ -43,10 +44,10 @@ func (suite *RequestVerificationTestSuite) SetupTest() { suite.request = types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -62,9 +63,9 @@ func (suite *RequestVerificationTestSuite) SetupTest() { k.SetRequest(ctx, types.RequestID(1), suite.request) k.SetRequestCount(ctx, 1) - err := k.GrantReporter(ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := k.GrantReporter(ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) expiration := ctx.BlockTime().Add(10 * time.Minute) - app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(testapp.Validators[0].ValAddress), + app.AuthzKeeper.SaveGrant(ctx, suite.granteeAddr, sdk.AccAddress(bandtesting.Validators[0].ValAddress), authz.NewGenericAuthorization("some url"), &expiration, ) suite.assert.NoError(err) @@ -73,7 +74,7 @@ func (suite *RequestVerificationTestSuite) SetupTest() { func (suite *RequestVerificationTestSuite) TestSuccess() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -82,7 +83,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -95,7 +96,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { expectedResult := &types.QueryRequestVerificationResponse{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -108,7 +109,7 @@ func (suite *RequestVerificationTestSuite) TestSuccess() { func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 2, ExternalId: 1, DataSourceId: 1, @@ -117,7 +118,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -135,7 +136,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestIDNotExist() { func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 6, ExternalId: 1, DataSourceId: 1, @@ -145,7 +146,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -158,7 +159,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { expectedResult := &types.QueryRequestVerificationResponse{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 6, ExternalId: 1, DataSourceId: 1, @@ -171,7 +172,7 @@ func (suite *RequestVerificationTestSuite) TestRequestInDelayRange() { func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 7, ExternalId: 1, DataSourceId: 1, @@ -181,7 +182,7 @@ func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -199,7 +200,7 @@ func (suite *RequestVerificationTestSuite) TestFailedExceedDelayRange() { func (suite *RequestVerificationTestSuite) TestFailedDataSourceIDNotMatch() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 2, @@ -208,7 +209,7 @@ func (suite *RequestVerificationTestSuite) TestFailedDataSourceIDNotMatch() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -237,7 +238,7 @@ func (suite *RequestVerificationTestSuite) TestFailedEmptyRequest() { func (suite *RequestVerificationTestSuite) TestFailedChainIDNotMatch() { req := &types.QueryRequestVerificationRequest{ ChainId: "other-chain-id", - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -246,7 +247,7 @@ func (suite *RequestVerificationTestSuite) TestFailedChainIDNotMatch() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -277,7 +278,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidValidatorAddr() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -295,7 +296,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidValidatorAddr() { func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -304,7 +305,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -322,7 +323,7 @@ func (suite *RequestVerificationTestSuite) TestFailedInvalidReporterPubKey() { func (suite *RequestVerificationTestSuite) TestFailedEmptySignature() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, Reporter: hex.EncodeToString(suite.reporterPrivKey.PubKey().Bytes()), @@ -335,12 +336,12 @@ func (suite *RequestVerificationTestSuite) TestFailedEmptySignature() { } func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { - err := suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + err := suite.querier.Keeper.RevokeReporter(suite.ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) suite.assert.NoError(err) req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -349,7 +350,7 @@ func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -365,12 +366,12 @@ func (suite *RequestVerificationTestSuite) TestFailedReporterUnauthorized() { } func (suite *RequestVerificationTestSuite) TestFailedUnselectedValidator() { - suite.request.RequestedValidators = []string{testapp.Validators[1].ValAddress.String()} + suite.request.RequestedValidators = []string{bandtesting.Validators[1].ValAddress.String()} suite.querier.Keeper.SetRequest(suite.ctx, types.RequestID(1), suite.request) req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -379,7 +380,7 @@ func (suite *RequestVerificationTestSuite) TestFailedUnselectedValidator() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -400,7 +401,7 @@ func (suite *RequestVerificationTestSuite) TestFailedNoDataSourceFound() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -409,7 +410,7 @@ func (suite *RequestVerificationTestSuite) TestFailedNoDataSourceFound() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -428,7 +429,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() err := suite.querier.Keeper.AddReport( suite.ctx, types.RequestID(1), - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -438,7 +439,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -447,7 +448,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -465,7 +466,7 @@ func (suite *RequestVerificationTestSuite) TestFailedValidatorAlreadyReported() func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { req := &types.QueryRequestVerificationRequest{ ChainId: suite.ctx.ChainID(), - Validator: testapp.Validators[0].ValAddress.String(), + Validator: bandtesting.Validators[0].ValAddress.String(), RequestId: 1, ExternalId: 1, DataSourceId: 1, @@ -476,7 +477,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { requestVerification := types.NewRequestVerification( req.ChainId, - testapp.Validators[0].ValAddress, + bandtesting.Validators[0].ValAddress, types.RequestID(req.RequestId), types.ExternalID(req.ExternalId), types.DataSourceID(req.DataSourceId), @@ -493,7 +494,7 @@ func (suite *RequestVerificationTestSuite) TestFailedRequestAlreadyExpired() { func (suite *RequestVerificationTestSuite) TestGetReporters() { req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -507,7 +508,7 @@ func (suite *RequestVerificationTestSuite) TestGetReporters() { func (suite *RequestVerificationTestSuite) TestGetExpiredReporters() { suite.ctx = suite.ctx.WithBlockTime(suite.ctx.BlockTime().Add(10 * time.Minute)) req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -520,7 +521,7 @@ func (suite *RequestVerificationTestSuite) TestGetExpiredReporters() { func (suite *RequestVerificationTestSuite) TestIsReporter() { req := &types.QueryIsReporterRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), ReporterAddress: suite.reporterAddr.String(), } res, err := suite.querier.IsReporter(sdk.WrapSDKContext(suite.ctx), req) @@ -534,7 +535,7 @@ func (suite *RequestVerificationTestSuite) TestIsReporter() { func (suite *RequestVerificationTestSuite) TestIsNotReporter() { req := &types.QueryIsReporterRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), ReporterAddress: suite.granteeAddr.String(), } res, err := suite.querier.IsReporter(sdk.WrapSDKContext(suite.ctx), req) @@ -547,9 +548,9 @@ func (suite *RequestVerificationTestSuite) TestIsNotReporter() { } func (suite *RequestVerificationTestSuite) TestRevokeReporters() { - suite.querier.Keeper.RevokeReporter(suite.ctx, testapp.Validators[0].ValAddress, suite.reporterAddr) + suite.querier.Keeper.RevokeReporter(suite.ctx, bandtesting.Validators[0].ValAddress, suite.reporterAddr) req := &types.QueryReportersRequest{ - ValidatorAddress: testapp.Validators[0].ValAddress.String(), + ValidatorAddress: bandtesting.Validators[0].ValAddress.String(), } res, err := suite.querier.Reporters(sdk.WrapSDKContext(suite.ctx), req) @@ -571,7 +572,8 @@ type PendingRequestsTestSuite struct { func (suite *PendingRequestsTestSuite) SetupTest() { suite.assert = require.New(suite.T()) - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(suite.T(), true) + k := app.OracleKeeper suite.querier = keeper.Querier{ Keeper: k, @@ -583,10 +585,10 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { assignedButPendingReq := types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -599,10 +601,10 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { notBeAssignedReq := types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[1].ValAddress}, + []sdk.ValAddress{bandtesting.Validators[1].ValAddress}, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -616,12 +618,12 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 1, BasicCalldata, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -635,12 +637,12 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { 1, BasicCalldata, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, 1, 1, - testapp.ParseTime(0), + bandtesting.ParseTime(0), "", []types.RawRequest{ types.NewRawRequest(1, 1, []byte("testdata")), @@ -660,7 +662,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 5, - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -669,7 +671,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 5, - types.NewReport(testapp.Validators[1].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -678,7 +680,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { suite.querier.Keeper.SetReport( suite.ctx, 6, - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("testdata")), types.NewRawReport(2, 0, []byte("testdata")), types.NewRawReport(3, 0, []byte("testdata")), @@ -686,7 +688,7 @@ func (suite *PendingRequestsTestSuite) TestSuccess() { ) r, err := suite.querier.PendingRequests(sdk.WrapSDKContext(suite.ctx), &types.QueryPendingRequestsRequest{ - ValidatorAddress: sdk.ValAddress(testapp.Validators[0].Address).String(), + ValidatorAddress: sdk.ValAddress(bandtesting.Validators[0].Address).String(), }) suite.assert.Equal(&types.QueryPendingRequestsResponse{RequestIDs: []uint64{3}}, r) diff --git a/x/oracle/keeper/keeper_test.go b/x/oracle/keeper/keeper_test.go index 7bc1c6dd6..4f619c8d5 100644 --- a/x/oracle/keeper/keeper_test.go +++ b/x/oracle/keeper/keeper_test.go @@ -5,12 +5,14 @@ import ( "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetSetRequestCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially request count must be 0. require.Equal(t, uint64(0), k.GetRequestCount(ctx)) // After we set the count manually, it should be reflected. @@ -19,25 +21,33 @@ func TestGetSetRequestCount(t *testing.T) { } func TestGetDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetDataSourceCount(ctx, 42) require.Equal(t, uint64(42), k.GetDataSourceCount(ctx)) } func TestGetSetOracleScriptCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetOracleScriptCount(ctx, 42) require.Equal(t, uint64(42), k.GetOracleScriptCount(ctx)) } func TestGetSetRollingSeed(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRollingSeed(ctx, []byte("HELLO_WORLD")) require.Equal(t, []byte("HELLO_WORLD"), k.GetRollingSeed(ctx)) } func TestGetNextRequestID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // First request id must be 1. require.Equal(t, types.RequestID(1), k.GetNextRequestID(ctx)) // After we add new requests, the request count must increase accordingly. @@ -49,7 +59,9 @@ func TestGetNextRequestID(t *testing.T) { } func TestGetNextDataSourceID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + initialID := k.GetDataSourceCount(ctx) require.Equal(t, types.DataSourceID(initialID+1), k.GetNextDataSourceID(ctx)) require.Equal(t, types.DataSourceID(initialID+2), k.GetNextDataSourceID(ctx)) @@ -57,7 +69,9 @@ func TestGetNextDataSourceID(t *testing.T) { } func TestGetNextOracleScriptID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + initialID := k.GetOracleScriptCount(ctx) require.Equal(t, types.OracleScriptID(initialID+1), k.GetNextOracleScriptID(ctx)) require.Equal(t, types.OracleScriptID(initialID+2), k.GetNextOracleScriptID(ctx)) @@ -65,7 +79,9 @@ func TestGetNextOracleScriptID(t *testing.T) { } func TestGetSetRequestLastExpiredID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially last expired request must be 0. require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) k.SetRequestLastExpired(ctx, 20) diff --git a/x/oracle/keeper/oracle_script_test.go b/x/oracle/keeper/oracle_script_test.go index 80bdeaa0d..977a50bc1 100644 --- a/x/oracle/keeper/oracle_script_test.go +++ b/x/oracle/keeper/oracle_script_test.go @@ -6,33 +6,38 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestHasOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a oracle script ID 42 without setting it. require.False(t, k.HasOracleScript(ctx, 42)) // After we set it, we should be able to find it. k.SetOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.True(t, k.HasOracleScript(ctx, 42)) } func TestSetterGetterOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent oracle script should return error. _, err := k.GetOracleScript(ctx, 42) require.ErrorIs(t, err, types.ErrOracleScriptNotFound) require.Panics(t, func() { _ = k.MustGetOracleScript(ctx, 42) }) // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, ) // Sets id 42 with oracle script 1 and id 42 with oracle script 2. k.SetOracleScript(ctx, 42, oracleScript1) @@ -53,13 +58,15 @@ func TestSetterGetterOracleScript(t *testing.T) { } func TestAddEditOracleScriptBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, + bandtesting.Bob.Address, "NAME2", "DESCRIPTION2", "FILENAME2", BasicSchema, BasicSourceCodeURL, ) // Adds a new oracle script to the store. We should be able to retrieve it back. id := k.AddOracleScript(ctx, oracleScript1) @@ -79,13 +86,15 @@ func TestAddEditOracleScriptBasic(t *testing.T) { } func TestAddEditOracleScriptDoNotModify(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Creates some basic oracle scripts. oracleScript1 := types.NewOracleScript( - testapp.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, + bandtesting.Alice.Address, "NAME1", "DESCRIPTION1", "FILENAME1", BasicSchema, BasicSourceCodeURL, ) oracleScript2 := types.NewOracleScript( - testapp.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", + bandtesting.Bob.Address, types.DoNotModify, types.DoNotModify, "FILENAME2", types.DoNotModify, types.DoNotModify, ) // Adds a new oracle script to the store. We should be able to retrieve it back. @@ -106,18 +115,20 @@ func TestAddEditOracleScriptDoNotModify(t *testing.T) { } func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially we expect the oracle script count to be what we have on genesis state. - genesisCount := uint64(len(testapp.OracleScripts)) - 1 + genesisCount := uint64(len(bandtesting.OracleScripts)) - 1 require.Equal(t, genesisCount, k.GetOracleScriptCount(ctx)) // Every new oracle script we add should return a new ID. id1 := k.AddOracleScript(ctx, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.Equal(t, types.OracleScriptID(genesisCount+1), id1) // Adds another oracle script so now ID should increase by 2. id2 := k.AddOracleScript(ctx, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) require.Equal(t, types.OracleScriptID(genesisCount+2), id2) // Finally we expect the oracle script to increase as well. @@ -125,28 +136,34 @@ func TestAddOracleScriptMustReturnCorrectID(t *testing.T) { } func TestEditNonExistentOracleScript(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Editing a non-existent oracle script should return error. require.Panics(t, func() { k.MustEditOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) }) } func TestGetAllOracleScripts(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should be able to get all genesis oracle scripts. - require.Equal(t, testapp.OracleScripts[1:], k.GetAllOracleScripts(ctx)) + require.Equal(t, bandtesting.OracleScripts[1:], k.GetAllOracleScripts(ctx)) } func TestAddOracleScriptFile(t *testing.T) { - _, _, k := testapp.CreateTestInput(true) + app, _ := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Code should be perferctly compilable. - compiledCode, err := testapp.OwasmVM.Compile(testapp.WasmExtra1, types.MaxCompiledWasmCodeSize) + compiledCode, err := bandtesting.OwasmVM.Compile(testdata.WasmExtra1, types.MaxCompiledWasmCodeSize) require.NoError(t, err) // We start by adding the Owasm content to the storage. - filename, err := k.AddOracleScriptFile(testapp.WasmExtra1) + filename, err := k.AddOracleScriptFile(testdata.WasmExtra1) require.NoError(t, err) // If we get by file name, we should get the compiled content back. require.Equal(t, compiledCode, k.GetFile(filename)) diff --git a/x/oracle/keeper/owasm_test.go b/x/oracle/keeper/owasm_test.go index 841aeef18..b07c64012 100644 --- a/x/oracle/keeper/owasm_test.go +++ b/x/oracle/keeper/owasm_test.go @@ -14,13 +14,16 @@ import ( "github.com/bandprotocol/chain/v2/pkg/obi" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/testing/testdata" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting 3 validators using ROLLING_SEED_1_WITH_LONG_ENOUGH_ENTROPY k.SetRollingSeed(ctx, []byte("ROLLING_SEED_1_WITH_LONG_ENOUGH_ENTROPY")) vals, err := k.GetRandomValidators(ctx, 3, 1) @@ -28,9 +31,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -41,9 +44,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -54,9 +57,9 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[2].ValAddress, - testapp.Validators[0].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) @@ -67,16 +70,18 @@ func TestGetRandomValidatorsSuccessActivateAll(t *testing.T) { require.Equal( t, []sdk.ValAddress{ - testapp.Validators[0].ValAddress, - testapp.Validators[2].ValAddress, - testapp.Validators[1].ValAddress, + bandtesting.Validators[0].ValAddress, + bandtesting.Validators[2].ValAddress, + bandtesting.Validators[1].ValAddress, }, vals, ) } func TestGetRandomValidatorsTooBigSize(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + _, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) _, err = k.GetRandomValidators(ctx, 2, 1) @@ -90,41 +95,49 @@ func TestGetRandomValidatorsTooBigSize(t *testing.T) { } func TestGetRandomValidatorsWithActivate(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + k.SetRollingSeed(ctx, []byte("ROLLING_SEED_WITH_LONG_ENOUGH_ENTROPY")) // If no validators are active, you must not be able to get random validators _, err := k.GetRandomValidators(ctx, 1, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // If we activate 2 validators, we should be able to get at most 2 from the function. - k.Activate(ctx, testapp.Validators[0].ValAddress) - k.Activate(ctx, testapp.Validators[1].ValAddress) + k.Activate(ctx, bandtesting.Validators[0].ValAddress) + k.Activate(ctx, bandtesting.Validators[1].ValAddress) vals, err := k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress}, vals) + require.Equal(t, []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, vals) vals, err = k.GetRandomValidators(ctx, 2, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, vals) + require.Equal( + t, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + vals, + ) _, err = k.GetRandomValidators(ctx, 3, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) // After we deactivate 1 validator due to missing a report, we can only get at most 1 validator. - k.MissReport(ctx, testapp.Validators[0].ValAddress, time.Now()) + k.MissReport(ctx, bandtesting.Validators[0].ValAddress, time.Now()) vals, err = k.GetRandomValidators(ctx, 1, 1) require.NoError(t, err) - require.Equal(t, []sdk.ValAddress{testapp.Validators[1].ValAddress}, vals) + require.Equal(t, []sdk.ValAddress{bandtesting.Validators[1].ValAddress}, vals) _, err = k.GetRandomValidators(ctx, 2, 1) require.ErrorIs(t, err, types.ErrInsufficientValidators) } func TestPrepareRequestSuccessBasic(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) feePayerBalances := balancesRes.Balances @@ -135,71 +148,71 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) require.Equal(t, types.NewRequest( - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, BasicCalldata, []sdk.ValAddress{bandtesting.Validators[0].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), types.NewRawRequest(2, 2, []byte("beeb")), types.NewRawRequest(3, 3, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, + }, nil, bandtesting.TestDefaultExecuteGas, ), k.MustGetRequest(ctx, 1)) require.Equal(t, sdk.Events{ sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( authtypes.EventTypeCoinSpent, - sdk.NewAttribute(authtypes.AttributeKeySpender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeySpender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeCoinReceived, - sdk.NewAttribute(authtypes.AttributeKeyReceiver, testapp.Treasury.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyReceiver, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( authtypes.EventTypeTransfer, - sdk.NewAttribute(authtypes.AttributeKeyRecipient, testapp.Treasury.Address.String()), - sdk.NewAttribute(authtypes.AttributeKeySender, testapp.FeePayer.Address.String()), - sdk.NewAttribute(sdk.AttributeKeyAmount, testapp.Coins1000000uband.String()), + sdk.NewAttribute(authtypes.AttributeKeyRecipient, bandtesting.Treasury.Address.String()), + sdk.NewAttribute(authtypes.AttributeKeySender, bandtesting.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeyAmount, bandtesting.Coins1000000uband.String()), ), sdk.NewEvent( sdk.EventTypeMessage, - sdk.NewAttribute(sdk.AttributeKeySender, testapp.FeePayer.Address.String()), + sdk.NewAttribute(sdk.AttributeKeySender, bandtesting.FeePayer.Address.String()), ), sdk.NewEvent( types.EventTypeRequest, sdk.NewAttribute(types.AttributeKeyID, "1"), @@ -210,25 +223,25 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { sdk.NewAttribute(types.AttributeKeyMinCount, "1"), sdk.NewAttribute(types.AttributeKeyGasUsed, "5294700000"), sdk.NewAttribute(types.AttributeKeyTotalFees, "3000000uband"), - sdk.NewAttribute(types.AttributeKeyValidator, testapp.Validators[0].ValAddress.String()), + sdk.NewAttribute(types.AttributeKeyValidator, bandtesting.Validators[0].ValAddress.String()), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "1"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[1].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[1].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "1"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "2"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[2].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[2].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "2"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), ), sdk.NewEvent( types.EventTypeRawRequest, sdk.NewAttribute(types.AttributeKeyDataSourceID, "3"), - sdk.NewAttribute(types.AttributeKeyDataSourceHash, testapp.DataSources[3].Filename), + sdk.NewAttribute(types.AttributeKeyDataSourceHash, bandtesting.DataSources[3].Filename), sdk.NewAttribute(types.AttributeKeyExternalID, "3"), sdk.NewAttribute(types.AttributeKeyCalldata, "beeb"), sdk.NewAttribute(types.AttributeKeyFee, "1000000uband"), @@ -238,18 +251,20 @@ func TestPrepareRequestSuccessBasic(t *testing.T) { // assert gas consumption params := k.GetParams(ctx) require.Equal(t, 2, wrappedGasMeter.CountRecord(params.BaseOwasmGas, "BASE_OWASM_FEE")) - require.Equal(t, 1, wrappedGasMeter.CountRecord(testapp.TestDefaultPrepareGas, "OWASM_PREPARE_FEE")) - require.Equal(t, 1, wrappedGasMeter.CountRecord(testapp.TestDefaultExecuteGas, "OWASM_EXECUTE_FEE")) + require.Equal(t, 1, wrappedGasMeter.CountRecord(bandtesting.TestDefaultPrepareGas, "OWASM_PREPARE_FEE")) + require.Equal(t, 1, wrappedGasMeter.CountRecord(bandtesting.TestDefaultExecuteGas, "OWASM_EXECUTE_FEE")) paid := sdk.NewCoins(sdk.NewInt64Coin("uband", 3000000)) feePayerBalances = feePayerBalances.Sub(paid...) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.Treasury.Address, paid) + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.Treasury.Address, paid) } func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) // OracleScript#1: Prepare asks for DS#1,2,3 with ExtID#1,2,3 and calldata "beeb" m := types.NewMsgRequestData( 1, @@ -257,12 +272,12 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, 1, BasicClientID, - testapp.EmptyCoins, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.EmptyCoins, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 1000000uband, max: 0uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -271,11 +286,11 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 1000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 2000000uband, max: 1000000uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -284,11 +299,11 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 2000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2000000uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -297,11 +312,11 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 2999999)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "require: 3000000uband, max: 2999999uband: not enough fee") m = types.NewMsgRequestData( 1, @@ -310,18 +325,20 @@ func TestPrepareRequestNotEnoughMaxFee(t *testing.T) { 1, BasicClientID, sdk.NewCoins(sdk.NewInt64Coin("uband", 3000000)), - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.FeePayer.Address, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.FeePayer.Address, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.NoError(t, err) require.Equal(t, types.RequestID(1), id) } func TestPrepareRequestNotEnoughFund(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) // OracleScript#1: Prepare asks for DS#1,2,3 with ExtID#1,2,3 and calldata "beeb" m := types.NewMsgRequestData( 1, @@ -329,37 +346,41 @@ func TestPrepareRequestNotEnoughFund(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.Alice.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.Alice.Address, nil) require.EqualError(t, err, "spendable balance is smaller than 1000000uband: insufficient funds") } func TestPrepareRequestInvalidCalldataSize(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 1, []byte(strings.Repeat("x", 2000)), 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "got: 2000, max: 512: too large calldata") } func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589790)).WithBlockHeight(42) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589790)).WithBlockHeight(42) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) m := types.NewMsgRequestData( @@ -368,12 +389,12 @@ func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { 1, 1, BasicClientID, - testapp.EmptyCoins, + bandtesting.EmptyCoins, 1, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) require.Contains(t, err.Error(), "out-of-gas") @@ -384,12 +405,14 @@ func TestPrepareRequestNotEnoughPrepareGas(t *testing.T) { } func TestPrepareRequestInvalidAskCountFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.MaxAskCount = 5 k.SetParams(ctx, params) - wrappedGasMeter := testapp.NewGasMeterWrapper(ctx.GasMeter()) + wrappedGasMeter := bandtesting.NewGasMeterWrapper(ctx.GasMeter()) ctx = ctx.WithGasMeter(wrappedGasMeter) m := types.NewMsgRequestData( @@ -398,12 +421,12 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 10, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInvalidAskCount) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -416,12 +439,12 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 4, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrInsufficientValidators) require.Equal(t, 0, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -434,12 +457,12 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) require.Equal(t, 2, wrappedGasMeter.CountDescriptor("BASE_OWASM_FEE")) @@ -448,7 +471,9 @@ func TestPrepareRequestInvalidAskCountFail(t *testing.T) { } func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 0 @@ -459,25 +484,27 @@ func TestPrepareRequestBaseOwasmFeePanic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(90000)) require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "BASE_OWASM_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) }, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.BaseOwasmGas = 100000 params.PerValidatorRequestGas = 50000 @@ -488,16 +515,16 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { 2, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(90000)) require.PanicsWithValue( t, sdk.ErrorOutOfGas{Descriptor: "PER_VALIDATOR_REQUEST_FEE"}, - func() { k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) }, + func() { k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) }, ) m = types.NewMsgRequestData( 1, @@ -505,117 +532,130 @@ func TestPrepareRequestPerValidatorRequestFeePanic(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) ctx = ctx.WithGasMeter(sdk.NewGasMeter(1000000)) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestEmptyCalldata(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) // Send nil while oracle script expects calldata + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Send nil while oracle script expects calldata m := types.NewMsgRequestData( 4, nil, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "runtime error while executing the Wasm script: bad wasm execution") } func TestPrepareRequestOracleScriptNotFound(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 999, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 999: oracle script not found") } func TestPrepareRequestBadWasmExecutionFail(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 2, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "OEI action to invoke is not available: bad wasm execution") } func TestPrepareRequestWithEmptyRawRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + m := types.NewMsgRequestData( 3, BasicCalldata, 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "empty raw requests") } func TestPrepareRequestUnknownDataSource(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - m := types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 99}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "id: 99: data source not found") } func TestPrepareRequestInvalidDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.MaxRawRequestCount = 3 k.SetParams(ctx, params) - m := types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ + m := types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3, 4}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address) - _, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address) + _, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.ErrorIs(t, err, types.ErrBadWasmExecution) - m = types.NewMsgRequestData(4, obi.MustEncode(testapp.Wasm4Input{ + m = types.NewMsgRequestData(4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2, 3}, Calldata: "beeb", - }), 1, 1, BasicClientID, testapp.Coins100000000uband, testapp.TestDefaultPrepareGas, testapp.TestDefaultExecuteGas, testapp.Alice.Address) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + }), 1, 1, BasicClientID, bandtesting.Coins100000000uband, bandtesting.TestDefaultPrepareGas, bandtesting.TestDefaultExecuteGas, bandtesting.Alice.Address) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) } func TestPrepareRequestTooMuchWasmGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper m := types.NewMsgRequestData( 5, @@ -623,12 +663,12 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) m = types.NewMsgRequestData( @@ -637,17 +677,18 @@ func TestPrepareRequestTooMuchWasmGas(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "out-of-gas while executing the wasm script: bad wasm execution") } func TestPrepareRequestTooLargeCalldata(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper m := types.NewMsgRequestData( 7, @@ -655,12 +696,12 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - id, err := k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + id, err := k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.Equal(t, types.RequestID(1), id) require.NoError(t, err) m = types.NewMsgRequestData( @@ -669,35 +710,45 @@ func TestPrepareRequestTooLargeCalldata(t *testing.T) { 1, 1, BasicClientID, - testapp.Coins100000000uband, - testapp.TestDefaultPrepareGas, - testapp.TestDefaultExecuteGas, - testapp.Alice.Address, + bandtesting.Coins100000000uband, + bandtesting.TestDefaultPrepareGas, + bandtesting.TestDefaultExecuteGas, + bandtesting.Alice.Address, ) - _, err = k.PrepareRequest(ctx, m, testapp.FeePayer.Address, nil) + _, err = k.PrepareRequest(ctx, m, bandtesting.FeePayer.Address, nil) require.EqualError(t, err, "span to write is too small: bad wasm execution") } func TestResolveRequestSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 1st Wasm - return "beeb" - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, + }, + nil, + bandtesting.TestDefaultExecuteGas, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) expectResult := types.NewResult( BasicClientID, 1, BasicCalldata, 2, 1, - 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), + 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, []byte("beeb"), ) require.Equal(t, expectResult, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -710,40 +761,42 @@ func TestResolveRequestSuccess(t *testing.T) { } func TestResolveRequestSuccessComplex(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 4th Wasm. Append all reports from all validators. - 4, obi.MustEncode(testapp.Wasm4Input{ + 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), - }), []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + }), []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, testapp.TestDefaultExecuteGas, + }, nil, bandtesting.TestDefaultExecuteGas, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v1")), types.NewRawReport(1, 0, []byte("beebd2v1")), }, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[1].ValAddress, true, []types.RawReport{ + bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, []byte("beebd2v2")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 4, obi.MustEncode(testapp.Wasm4Input{ + BasicClientID, 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), }), 2, 1, - 42, 2, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, - obi.MustEncode(testapp.Wasm4Output{Ret: "beebd1v1beebd1v2beebd2v1beebd2v2"}), + 42, 2, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, + obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v1beebd1v2beebd2v1beebd2v2"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -759,64 +812,76 @@ func TestResolveRequestSuccessComplex(t *testing.T) { } func TestResolveRequestOutOfGas(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 1st Wasm - return "beeb" - 1, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 1, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 0, + }, + nil, + 0, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( BasicClientID, 1, BasicCalldata, 2, 1, - 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) } func TestResolveReadNilExternalData(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 4th Wasm. Append all reports from all validators. - 4, obi.MustEncode(testapp.Wasm4Input{ + 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), - }), []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + }), []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, 1, + 42, bandtesting.ParseTime(1581589790), BasicClientID, []types.RawRequest{ types.NewRawRequest(0, 1, BasicCalldata), types.NewRawRequest(1, 2, BasicCalldata), - }, nil, testapp.TestDefaultExecuteGas, + }, nil, bandtesting.TestDefaultExecuteGas, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, nil), types.NewRawReport(1, 0, []byte("beebd2v1")), }, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[1].ValAddress, true, []types.RawReport{ + bandtesting.Validators[1].ValAddress, true, []types.RawReport{ types.NewRawReport(0, 0, []byte("beebd1v2")), types.NewRawReport(1, 0, nil), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 4, obi.MustEncode(testapp.Wasm4Input{ + BasicClientID, 4, obi.MustEncode(testdata.Wasm4Input{ IDs: []int64{1, 2}, Calldata: string(BasicCalldata), }), 2, 1, - 42, 2, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, - obi.MustEncode(testapp.Wasm4Output{Ret: "beebd1v2beebd2v1"}), + 42, 2, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_SUCCESS, + obi.MustEncode(testdata.Wasm4Output{Ret: "beebd1v2beebd2v1"}), ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -829,24 +894,34 @@ func TestResolveReadNilExternalData(t *testing.T) { } func TestResolveRequestNoReturnData(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 3rd Wasm - do nothing - 3, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 3, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 1, + }, + nil, + 1, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 3, BasicCalldata, 2, 1, 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 3, BasicCalldata, 2, 1, 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -858,24 +933,34 @@ func TestResolveRequestNoReturnData(t *testing.T) { } func TestResolveRequestWasmFailure(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 6th Wasm - out-of-gas - 6, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 6, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, 0, + }, + nil, + 0, )) k.SetReport(ctx, 42, types.NewReport( - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(1, 0, []byte("beeb")), }, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 6, BasicCalldata, 2, 1, 42, 1, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 6, BasicCalldata, 2, 1, 42, 1, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) require.Equal(t, sdk.Events{sdk.NewEvent( @@ -887,20 +972,30 @@ func TestResolveRequestWasmFailure(t *testing.T) { } func TestResolveRequestCallReturnDataSeveralTimes(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(1581589890)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(1581589890)) k.SetRequest(ctx, 42, types.NewRequest( // 9th Wasm - set return data several times - 9, BasicCalldata, []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, 1, - 42, testapp.ParseTime(1581589790), BasicClientID, []types.RawRequest{ + 9, + BasicCalldata, + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 1, + 42, + bandtesting.ParseTime(1581589790), + BasicClientID, + []types.RawRequest{ types.NewRawRequest(1, 1, []byte("beeb")), - }, nil, testapp.TestDefaultExecuteGas, + }, + nil, + bandtesting.TestDefaultExecuteGas, )) k.ResolveRequest(ctx, 42) result := types.NewResult( - BasicClientID, 9, BasicCalldata, 2, 1, 42, 0, testapp.ParseTime(1581589790).Unix(), - testapp.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, + BasicClientID, 9, BasicCalldata, 2, 1, 42, 0, bandtesting.ParseTime(1581589790).Unix(), + bandtesting.ParseTime(1581589890).Unix(), types.RESOLVE_STATUS_FAILURE, nil, ) require.Equal(t, result, k.MustGetResult(ctx, 42)) @@ -916,12 +1011,12 @@ func rawRequestsFromFees(ctx sdk.Context, k keeper.Keeper, fees []sdk.Coins) []t var rawRequests []types.RawRequest for _, f := range fees { id := k.AddDataSource(ctx, types.NewDataSource( - testapp.Owner.Address, + bandtesting.Owner.Address, "mock ds", "there is no real code", "no file", f, - testapp.Treasury.Address, + bandtesting.Treasury.Address, )) rawRequests = append(rawRequests, types.NewRawRequest( @@ -933,129 +1028,134 @@ func rawRequestsFromFees(ctx sdk.Context, k keeper.Keeper, fees []sdk.Coins) []t } func TestCollectFeeEmptyFee(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.Alice.Address, testapp.EmptyCoins, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.EmptyCoins, 1, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 1, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 1, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.EmptyCoins, 2, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.EmptyCoins, 2, raws) require.NoError(t, err) require.Empty(t, coins) - coins, err = k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 2, raws) + coins, err = k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 2, raws) require.NoError(t, err) require.Empty(t, coins) } func TestCollectFeeBasicSuccess(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) feePayerBalances := balancesRes.Balances feePayerBalances[0].Amount = feePayerBalances[0].Amount.Sub(sdk.NewInt(3000000)) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins100000000uband, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins100000000uband, 1, raws) require.NoError(t, err) require.Equal(t, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), coins) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances( + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) } func TestCollectFeeBasicSuccessWithOtherAskCount(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) balancesRes, err := app.BankKeeper.AllBalances( sdk.WrapSDKContext(ctx), - authtypes.NewQueryAllBalancesRequest(testapp.FeePayer.Address, &query.PageRequest{}), + authtypes.NewQueryAllBalancesRequest(bandtesting.FeePayer.Address, &query.PageRequest{}), ) feePayerBalances := balancesRes.Balances feePayerBalances[0].Amount = feePayerBalances[0].Amount.Sub(sdk.NewInt(12000000)) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins100000000uband, 4, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins100000000uband, 4, raws) require.NoError(t, err) require.Equal(t, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(12000000))), coins) - testapp.CheckBalances(t, ctx, app.BankKeeper, testapp.FeePayer.Address, feePayerBalances) - testapp.CheckBalances( + bandtesting.CheckBalances(t, ctx, app.BankKeeper, bandtesting.FeePayer.Address, feePayerBalances) + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(12000000))), ) } func TestCollectFeeWithMixedAndFeeNotEnough(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.FeePayer.Address, testapp.EmptyCoins, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.EmptyCoins, 1, raws) require.ErrorIs(t, err, types.ErrNotEnoughFee) require.Nil(t, coins) - coins, err = k.CollectFee(ctx, testapp.FeePayer.Address, testapp.Coins1000000uband, 1, raws) + coins, err = k.CollectFee(ctx, bandtesting.FeePayer.Address, bandtesting.Coins1000000uband, 1, raws) require.ErrorIs(t, err, types.ErrNotEnoughFee) require.Nil(t, coins) } func TestCollectFeeWithEnoughFeeButInsufficientBalance(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) - coins, err := k.CollectFee(ctx, testapp.Alice.Address, testapp.Coins100000000uband, 1, raws) + coins, err := k.CollectFee(ctx, bandtesting.Alice.Address, bandtesting.Coins100000000uband, 1, raws) require.Nil(t, coins) // MAX is 100m but have only 1m in account // First ds collect 1m so there no balance enough for next ds but it doesn't touch limit @@ -1063,14 +1163,15 @@ func TestCollectFeeWithEnoughFeeButInsufficientBalance(t *testing.T) { } func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000)))) @@ -1079,14 +1180,14 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(2000000))), ) coins, err := k.CollectFee( ctx, - testapp.FeePayer.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.FeePayer.Address), + bandtesting.FeePayer.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.FeePayer.Address), 1, raws, ) @@ -1103,35 +1204,36 @@ func TestCollectFeeWithWithManyUnitSuccess(t *testing.T) { // start: 100band, 0abc // top-up: 100band, 2abc // collect 3 band and 1 abc => 97band, 1abc - testapp.CheckBalances( + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.FeePayer.Address, + bandtesting.FeePayer.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(97000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) // Treasury balance // start: 0band, 0abc // collect 3 band and 1 abc => 3band, 1abc - testapp.CheckBalances( + bandtesting.CheckBalances( t, ctx, app.BankKeeper, - testapp.Treasury.Address, + bandtesting.Treasury.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) } func TestCollectFeeWithWithManyUnitFail(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper raws := rawRequestsFromFees(ctx, k, []sdk.Coins{ - testapp.EmptyCoins, - testapp.Coins1000000uband, - testapp.EmptyCoins, + bandtesting.EmptyCoins, + bandtesting.Coins1000000uband, + bandtesting.EmptyCoins, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(2000000)), sdk.NewCoin("uabc", sdk.NewInt(1000000))), - testapp.EmptyCoins, + bandtesting.EmptyCoins, }) app.BankKeeper.MintCoins( @@ -1144,28 +1246,28 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Bob.Address, + bandtesting.Bob.Address, sdk.NewCoins(sdk.NewCoin("uband", sdk.NewInt(3000000))), ) app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Bob.Address, + bandtesting.Bob.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1))), ) // Carol have not enough uband but have enough uabc app.BankKeeper.SendCoinsFromModuleToAccount( ctx, minttypes.ModuleName, - testapp.Carol.Address, + bandtesting.Carol.Address, sdk.NewCoins(sdk.NewCoin("uabc", sdk.NewInt(1000000))), ) // Alice _, err := k.CollectFee( ctx, - testapp.Alice.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Alice.Address), + bandtesting.Alice.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Alice.Address), 1, raws, ) @@ -1174,8 +1276,8 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { // Bob _, err = k.CollectFee( ctx, - testapp.Bob.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Bob.Address), + bandtesting.Bob.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Bob.Address), 1, raws, ) @@ -1184,8 +1286,8 @@ func TestCollectFeeWithWithManyUnitFail(t *testing.T) { // Carol _, err = k.CollectFee( ctx, - testapp.Carol.Address, - testapp.MustGetBalances(ctx, app.BankKeeper, testapp.Carol.Address), + bandtesting.Carol.Address, + bandtesting.MustGetBalances(ctx, app.BankKeeper, bandtesting.Carol.Address), 1, raws, ) diff --git a/x/oracle/keeper/params_test.go b/x/oracle/keeper/params_test.go index 9b94a8473..7308e93cd 100644 --- a/x/oracle/keeper/params_test.go +++ b/x/oracle/keeper/params_test.go @@ -6,12 +6,14 @@ import ( "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestGetSetParams(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + expectedParams := types.Params{ MaxRawRequestCount: 1, MaxAskCount: 10, diff --git a/x/oracle/keeper/report_test.go b/x/oracle/keeper/report_test.go index 1a3c33d4a..144c3d713 100644 --- a/x/oracle/keeper/report_test.go +++ b/x/oracle/keeper/report_test.go @@ -6,15 +6,15 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func defaultRequest() types.Request { return types.NewRequest( 1, BasicCalldata, - []sdk.ValAddress{testapp.Validators[0].ValAddress, testapp.Validators[1].ValAddress}, - 2, 0, testapp.ParseTime(0), + []sdk.ValAddress{bandtesting.Validators[0].ValAddress, bandtesting.Validators[1].ValAddress}, + 2, 0, bandtesting.ParseTime(0), BasicClientID, []types.RawRequest{ types.NewRawRequest(42, 1, BasicCalldata), types.NewRawRequest(43, 2, BasicCalldata), @@ -23,26 +23,30 @@ func defaultRequest() types.Request { } func TestHasReport(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a report to request ID 42 from Alice without setting it. - require.False(t, k.HasReport(ctx, 42, testapp.Alice.ValAddress)) + require.False(t, k.HasReport(ctx, 42, bandtesting.Alice.ValAddress)) // After we set it, we should be able to find it. - k.SetReport(ctx, 42, types.NewReport(testapp.Alice.ValAddress, true, nil)) - require.True(t, k.HasReport(ctx, 42, testapp.Alice.ValAddress)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Alice.ValAddress, true, nil)) + require.True(t, k.HasReport(ctx, 42, bandtesting.Alice.ValAddress)) } func TestAddReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, ) require.NoError(t, err) require.Equal(t, []types.Report{ - types.NewReport(testapp.Validators[0].ValAddress, true, []types.RawReport{ + types.NewReport(bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }), @@ -50,9 +54,11 @@ func TestAddReportSuccess(t *testing.T) { } func TestReportOnNonExistingRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -61,10 +67,12 @@ func TestReportOnNonExistingRequest(t *testing.T) { } func TestReportByNotRequestedValidator(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Alice.ValAddress, true, []types.RawReport{ + bandtesting.Alice.ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -73,17 +81,19 @@ func TestReportByNotRequestedValidator(t *testing.T) { } func TestDuplicateReport(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, ) require.NoError(t, err) err = k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(43, 1, []byte("data2/1")), }, @@ -92,10 +102,12 @@ func TestDuplicateReport(t *testing.T) { } func TestReportInvalidDataSourceCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), }, ) @@ -103,10 +115,12 @@ func TestReportInvalidDataSourceCount(t *testing.T) { } func TestReportInvalidExternalIDs(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 1, defaultRequest()) err := k.AddReport(ctx, 1, - testapp.Validators[0].ValAddress, true, []types.RawReport{ + bandtesting.Validators[0].ValAddress, true, []types.RawReport{ types.NewRawReport(42, 0, []byte("data1/1")), types.NewRawReport(44, 1, []byte("data2/1")), // BAD EXTERNAL ID! }, @@ -115,37 +129,41 @@ func TestReportInvalidExternalIDs(t *testing.T) { } func TestGetReportCount(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting some aribrary reports. - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Carol.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Carol.ValAddress, true, []types.RawReport{})) // GetReportCount should return the correct values. require.Equal(t, uint64(2), k.GetReportCount(ctx, types.RequestID(1))) require.Equal(t, uint64(3), k.GetReportCount(ctx, types.RequestID(2))) } func TestDeleteReports(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting some arbitrary reports. - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(1), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Alice.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Bob.ValAddress, true, []types.RawReport{})) - k.SetReport(ctx, types.RequestID(2), types.NewReport(testapp.Carol.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(1), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Alice.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Bob.ValAddress, true, []types.RawReport{})) + k.SetReport(ctx, types.RequestID(2), types.NewReport(bandtesting.Carol.ValAddress, true, []types.RawReport{})) // All reports should exist on the state. - require.True(t, k.HasReport(ctx, types.RequestID(1), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(1), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Carol.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Carol.ValAddress)) // After we delete reports related to request#1, they must disappear. k.DeleteReports(ctx, types.RequestID(1)) - require.False(t, k.HasReport(ctx, types.RequestID(1), testapp.Alice.ValAddress)) - require.False(t, k.HasReport(ctx, types.RequestID(1), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Alice.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Bob.ValAddress)) - require.True(t, k.HasReport(ctx, types.RequestID(2), testapp.Carol.ValAddress)) + require.False(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Alice.ValAddress)) + require.False(t, k.HasReport(ctx, types.RequestID(1), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Alice.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Bob.ValAddress)) + require.True(t, k.HasReport(ctx, types.RequestID(2), bandtesting.Carol.ValAddress)) } diff --git a/x/oracle/keeper/request_test.go b/x/oracle/keeper/request_test.go index 4bf0f533a..c0f802033 100644 --- a/x/oracle/keeper/request_test.go +++ b/x/oracle/keeper/request_test.go @@ -6,7 +6,7 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -34,18 +34,22 @@ func testRequest( } func TestHasRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We should not have a request ID 42 without setting it. require.False(t, k.HasRequest(ctx, 42)) // After we set it, we should be able to find it. - k.SetRequest(ctx, 42, types.NewRequest(1, BasicCalldata, nil, 1, 1, testapp.ParseTime(0), "", nil, nil, 0)) + k.SetRequest(ctx, 42, types.NewRequest(1, BasicCalldata, nil, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0)) require.True(t, k.HasRequest(ctx, 42)) } func TestDeleteRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // After we set it, we should be able to find it. - k.SetRequest(ctx, 42, types.NewRequest(1, BasicCalldata, nil, 1, 1, testapp.ParseTime(0), "", nil, nil, 0)) + k.SetRequest(ctx, 42, types.NewRequest(1, BasicCalldata, nil, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0)) require.True(t, k.HasRequest(ctx, 42)) // After we delete it, we should not find it anymore. k.DeleteRequest(ctx, 42) @@ -56,14 +60,16 @@ func TestDeleteRequest(t *testing.T) { } func TestSetterGetterRequest(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Getting a non-existent request should return error. _, err := k.GetRequest(ctx, 42) require.ErrorIs(t, err, types.ErrRequestNotFound) require.Panics(t, func() { _ = k.MustGetRequest(ctx, 42) }) // Creates some basic requests. - req1 := types.NewRequest(1, BasicCalldata, nil, 1, 1, testapp.ParseTime(0), "", nil, nil, 0) - req2 := types.NewRequest(2, BasicCalldata, nil, 1, 1, testapp.ParseTime(0), "", nil, nil, 0) + req1 := types.NewRequest(1, BasicCalldata, nil, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0) + req2 := types.NewRequest(2, BasicCalldata, nil, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0) // Sets id 42 with request 1 and id 42 with request 2. k.SetRequest(ctx, 42, req1) k.SetRequest(ctx, 43, req2) @@ -83,7 +89,9 @@ func TestSetterGetterRequest(t *testing.T) { } func TestSetterGettterPendingResolveList(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially, we should get an empty list of pending resolves. require.Equal(t, k.GetPendingResolveList(ctx), []types.RequestID{}) // After we set something, we should get that thing back. @@ -98,27 +106,31 @@ func TestSetterGettterPendingResolveList(t *testing.T) { } func TestAddDataSourceBasic(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting an oracle request available at ID 42. k.SetOracleScript(ctx, 42, types.NewOracleScript( - testapp.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, + bandtesting.Owner.Address, BasicName, BasicDesc, BasicFilename, BasicSchema, BasicSourceCodeURL, )) // Adding the first request should return ID 1. id := k.AddRequest( ctx, - types.NewRequest(42, BasicCalldata, []sdk.ValAddress{}, 1, 1, testapp.ParseTime(0), "", nil, nil, 0), + types.NewRequest(42, BasicCalldata, []sdk.ValAddress{}, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0), ) require.Equal(t, id, types.RequestID(1)) // Adding another request should return ID 2. id = k.AddRequest( ctx, - types.NewRequest(42, BasicCalldata, []sdk.ValAddress{}, 1, 1, testapp.ParseTime(0), "", nil, nil, 0), + types.NewRequest(42, BasicCalldata, []sdk.ValAddress{}, 1, 1, bandtesting.ParseTime(0), "", nil, nil, 0), ) require.Equal(t, id, types.RequestID(2)) } func TestAddPendingResolveList(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // Initially, we should get an empty list of pending resolves. require.Equal(t, k.GetPendingResolveList(ctx), []types.RequestID{}) // Everytime we append a new request ID, it should show up. @@ -129,7 +141,9 @@ func TestAddPendingResolveList(t *testing.T) { } func TestProcessExpiredRequests(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + params := k.GetParams(ctx) params.ExpirationBlockCount = 3 k.SetParams(ctx, params) @@ -149,18 +163,18 @@ func TestProcessExpiredRequests(t *testing.T) { k.AddRequest(ctx, req4) // Initially all validators are active. - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) // Validator 1 reports all requests. Validator 2 misses request#3. rawReports := []types.RawReport{types.NewRawReport(42, 0, BasicReport), types.NewRawReport(43, 0, BasicReport)} - k.AddReport(ctx, 1, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 2, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 3, testapp.Validators[0].ValAddress, false, rawReports) - k.AddReport(ctx, 4, testapp.Validators[0].ValAddress, true, rawReports) - k.AddReport(ctx, 1, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 2, testapp.Validators[1].ValAddress, true, rawReports) - k.AddReport(ctx, 4, testapp.Validators[1].ValAddress, true, rawReports) + k.AddReport(ctx, 1, bandtesting.Validators[0].ValAddress, false, rawReports) + k.AddReport(ctx, 2, bandtesting.Validators[0].ValAddress, true, rawReports) + k.AddReport(ctx, 3, bandtesting.Validators[0].ValAddress, false, rawReports) + k.AddReport(ctx, 4, bandtesting.Validators[0].ValAddress, true, rawReports) + k.AddReport(ctx, 1, bandtesting.Validators[1].ValAddress, true, rawReports) + k.AddReport(ctx, 2, bandtesting.Validators[1].ValAddress, true, rawReports) + k.AddReport(ctx, 4, bandtesting.Validators[1].ValAddress, true, rawReports) // Request 1, 2 and 4 gets resolved. Request 3 does not. k.ResolveSuccess(ctx, 1, BasicResult, 1234) @@ -170,31 +184,31 @@ func TestProcessExpiredRequests(t *testing.T) { require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) // At block 7, nothing should happen. - ctx = ctx.WithBlockHeight(7).WithBlockTime(testapp.ParseTime(7000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(7).WithBlockTime(bandtesting.ParseTime(7000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(0), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 2, true) testRequest(t, k, ctx, types.RequestID(2), types.RESOLVE_STATUS_FAILURE, 2, true) testRequest(t, k, ctx, types.RequestID(3), types.RESOLVE_STATUS_OPEN, 1, true) testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 8, now last request ID should move to 1. No events should be emitted. - ctx = ctx.WithBlockHeight(8).WithBlockTime(testapp.ParseTime(8000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(8).WithBlockTime(bandtesting.ParseTime(8000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(1), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) testRequest(t, k, ctx, types.RequestID(2), types.RESOLVE_STATUS_FAILURE, 2, true) testRequest(t, k, ctx, types.RequestID(3), types.RESOLVE_STATUS_OPEN, 1, true) testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 9, request#3 is expired and validator 2 becomes inactive. - ctx = ctx.WithBlockHeight(9).WithBlockTime(testapp.ParseTime(9000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(9).WithBlockTime(bandtesting.ParseTime(9000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{sdk.NewEvent( types.EventTypeResolve, @@ -202,14 +216,14 @@ func TestProcessExpiredRequests(t *testing.T) { sdk.NewAttribute(types.AttributeKeyResolveStatus, "3"), ), sdk.NewEvent( types.EventTypeDeactivate, - sdk.NewAttribute(types.AttributeKeyValidator, testapp.Validators[1].ValAddress.String()), + sdk.NewAttribute(types.AttributeKeyValidator, bandtesting.Validators[1].ValAddress.String()), )}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(3), k.GetRequestLastExpired(ctx)) - require.True(t, k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress).IsActive) - require.False(t, k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress).IsActive) + require.True(t, k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress).IsActive) + require.False(t, k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress).IsActive) require.Equal(t, types.NewResult( BasicClientID, req3.OracleScriptID, req3.Calldata, uint64(len(req3.RequestedValidators)), req3.MinCount, - 3, 1, int64(req3.RequestTime), testapp.ParseTime(9000).Unix(), + 3, 1, int64(req3.RequestTime), bandtesting.ParseTime(9000).Unix(), types.RESOLVE_STATUS_EXPIRED, nil, ), k.MustGetResult(ctx, 3)) testRequest(t, k, ctx, types.RequestID(1), types.RESOLVE_STATUS_SUCCESS, 0, false) @@ -218,7 +232,7 @@ func TestProcessExpiredRequests(t *testing.T) { testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 10, nothing should happen - ctx = ctx.WithBlockHeight(10).WithBlockTime(testapp.ParseTime(10000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(10).WithBlockTime(bandtesting.ParseTime(10000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(3), k.GetRequestLastExpired(ctx)) @@ -228,7 +242,7 @@ func TestProcessExpiredRequests(t *testing.T) { testRequest(t, k, ctx, types.RequestID(4), types.RESOLVE_STATUS_SUCCESS, 2, true) // At block 13, last expired request becomes 4. - ctx = ctx.WithBlockHeight(13).WithBlockTime(testapp.ParseTime(13000)).WithEventManager(sdk.NewEventManager()) + ctx = ctx.WithBlockHeight(13).WithBlockTime(bandtesting.ParseTime(13000)).WithEventManager(sdk.NewEventManager()) k.ProcessExpiredRequests(ctx) require.Equal(t, sdk.Events{}, ctx.EventManager().Events()) require.Equal(t, types.RequestID(4), k.GetRequestLastExpired(ctx)) diff --git a/x/oracle/keeper/result_test.go b/x/oracle/keeper/result_test.go index 2e98c6fdb..98254c0a1 100644 --- a/x/oracle/keeper/result_test.go +++ b/x/oracle/keeper/result_test.go @@ -6,12 +6,14 @@ import ( sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/types" ) func TestResultBasicFunctions(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + // We start by setting result of request#1. result := types.NewResult( "alice", 1, BasicCalldata, 1, 1, 1, 1, 1589535020, 1589535022, 1, BasicResult, @@ -33,14 +35,16 @@ func TestResultBasicFunctions(t *testing.T) { } func TestSaveResultOK(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) - ctx = ctx.WithBlockTime(testapp.ParseTime(200)) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + ctx = ctx.WithBlockTime(bandtesting.ParseTime(200)) k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.SaveResult(ctx, 42, types.RESOLVE_STATUS_SUCCESS, BasicResult) expect := types.NewResult( - BasicClientID, 1, BasicCalldata, 2, 2, 42, 1, testapp.ParseTime(0).Unix(), - testapp.ParseTime(200).Unix(), types.RESOLVE_STATUS_SUCCESS, BasicResult, + BasicClientID, 1, BasicCalldata, 2, 2, 42, 1, bandtesting.ParseTime(0).Unix(), + bandtesting.ParseTime(200).Unix(), types.RESOLVE_STATUS_SUCCESS, BasicResult, ) result, err := k.GetResult(ctx, 42) require.NoError(t, err) @@ -48,9 +52,11 @@ func TestSaveResultOK(t *testing.T) { } func TestResolveSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveSuccess(ctx, 42, BasicResult, 1234) require.Equal(t, types.RESOLVE_STATUS_SUCCESS, k.MustGetResult(ctx, 42).ResolveStatus) require.Equal(t, BasicResult, k.MustGetResult(ctx, 42).Result) @@ -64,9 +70,11 @@ func TestResolveSuccess(t *testing.T) { } func TestResolveFailure(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveFailure(ctx, 42, "REASON") require.Equal(t, types.RESOLVE_STATUS_FAILURE, k.MustGetResult(ctx, 42).ResolveStatus) require.Empty(t, k.MustGetResult(ctx, 42).Result) @@ -79,9 +87,11 @@ func TestResolveFailure(t *testing.T) { } func TestResolveExpired(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(true) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + k.SetRequest(ctx, 42, defaultRequest()) // See report_test.go - k.SetReport(ctx, 42, types.NewReport(testapp.Validators[0].ValAddress, true, nil)) + k.SetReport(ctx, 42, types.NewReport(bandtesting.Validators[0].ValAddress, true, nil)) k.ResolveExpired(ctx, 42) require.Equal(t, types.RESOLVE_STATUS_EXPIRED, k.MustGetResult(ctx, 42).ResolveStatus) require.Empty(t, k.MustGetResult(ctx, 42).Result) diff --git a/x/oracle/keeper/snapshotter_integration_test.go b/x/oracle/keeper/snapshotter_integration_test.go index 16019930c..89f013272 100644 --- a/x/oracle/keeper/snapshotter_integration_test.go +++ b/x/oracle/keeper/snapshotter_integration_test.go @@ -3,17 +3,19 @@ package keeper_test import ( "testing" - "github.com/bandprotocol/chain/v2/testing/testapp" - "github.com/bandprotocol/chain/v2/x/oracle/keeper" tmproto "github.com/cometbft/cometbft/proto/tendermint/types" sdk "github.com/cosmos/cosmos-sdk/types" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + bandtesting "github.com/bandprotocol/chain/v2/testing" + "github.com/bandprotocol/chain/v2/x/oracle/keeper" ) func TestSnapshotter(t *testing.T) { // setup source app - srcApp, srcCtx, srcKeeper := testapp.CreateTestInput(true) + srcApp, srcCtx := bandtesting.CreateTestApp(t, true) + srcKeeper := srcApp.OracleKeeper // create snapshot srcApp.Commit() @@ -24,7 +26,7 @@ func TestSnapshotter(t *testing.T) { assert.NotNil(t, snapshot) // restore snapshot - destApp := testapp.SetupWithEmptyStore() + destApp := bandtesting.SetupWithEmptyStore(t, "testing") destCtx := destApp.NewUncachedContext(false, tmproto.Header{}) destKeeper := destApp.OracleKeeper require.NoError(t, destApp.SnapshotManager().Restore(*snapshot)) diff --git a/x/oracle/keeper/validator_status_test.go b/x/oracle/keeper/validator_status_test.go index 94dbac3f9..b0ea6740b 100644 --- a/x/oracle/keeper/validator_status_test.go +++ b/x/oracle/keeper/validator_status_test.go @@ -11,7 +11,8 @@ import ( minttypes "github.com/cosmos/cosmos-sdk/x/mint/types" "github.com/stretchr/testify/require" - "github.com/bandprotocol/chain/v2/testing/testapp" + bandapp "github.com/bandprotocol/chain/v2/app" + bandtesting "github.com/bandprotocol/chain/v2/testing" "github.com/bandprotocol/chain/v2/x/oracle/keeper" "github.com/bandprotocol/chain/v2/x/oracle/types" ) @@ -19,26 +20,26 @@ import ( func defaultVotes() []abci.VoteInfo { return []abci.VoteInfo{{ Validator: abci.Validator{ - Address: testapp.Validators[0].PubKey.Address(), + Address: bandtesting.Validators[0].PubKey.Address(), Power: 70, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[1].PubKey.Address(), + Address: bandtesting.Validators[1].PubKey.Address(), Power: 20, }, SignedLastBlock: true, }, { Validator: abci.Validator{ - Address: testapp.Validators[2].PubKey.Address(), + Address: bandtesting.Validators[2].PubKey.Address(), Power: 10, }, SignedLastBlock: true, }} } -func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { +func SetupFeeCollector(app *bandapp.BandApp, ctx sdk.Context, k keeper.Keeper) authtypes.ModuleAccountI { // Set collected fee to 1000000uband and 70% oracle reward proportion. feeCollector := app.AccountKeeper.GetModuleAccount(ctx, authtypes.FeeCollectorName) app.BankKeeper.MintCoins(ctx, minttypes.ModuleName, Coins1000000uband) @@ -58,8 +59,10 @@ func SetupFeeCollector(app *testapp.TestingApp, ctx sdk.Context, k keeper.Keeper } func TestAllocateTokenNoActiveValidators(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // No active oracle validators so nothing should happen. @@ -71,12 +74,14 @@ func TestAllocateTokenNoActiveValidators(t *testing.T) { } func TestAllocateTokensOneActive(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(false) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest goes to the only active validator. - k.Activate(ctx, testapp.Validators[1].ValAddress) + k.Activate(ctx, bandtesting.Validators[1].ValAddress) k.AllocateTokens(ctx, defaultVotes()) distAccount := app.AccountKeeper.GetModuleAccount(ctx, disttypes.ModuleName) @@ -95,18 +100,20 @@ func TestAllocateTokensOneActive(t *testing.T) { sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(14000)}}, app.DistrKeeper.GetFeePool(ctx).CommunityPool, ) - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress)) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(686000)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) - require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress)) + require.Empty(t, app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress)) } func TestAllocateTokensAllActive(t *testing.T) { - app, ctx, k := testapp.CreateTestInput(true) - feeCollector := SetupFeeCollector(app, ctx, k) + app, ctx := bandtesting.CreateTestApp(t, true) + k := app.OracleKeeper + + feeCollector := SetupFeeCollector(app.BandApp, ctx, k) require.Equal(t, Coins1000000uband, app.BankKeeper.GetAllBalances(ctx, feeCollector.GetAddress())) // From 70% of fee, 2% should go to community pool, the rest get split to validators. @@ -131,114 +138,130 @@ func TestAllocateTokensAllActive(t *testing.T) { require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(480200)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[0].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[0].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(137200)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[1].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[1].ValAddress).Rewards, ) require.Equal( t, sdk.DecCoins{{Denom: "uband", Amount: sdk.NewDec(68600)}}, - app.DistrKeeper.GetValidatorOutstandingRewards(ctx, testapp.Validators[2].ValAddress).Rewards, + app.DistrKeeper.GetValidatorOutstandingRewards(ctx, bandtesting.Validators[2].ValAddress).Rewards, ) } func TestGetDefaultValidatorStatus(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestGetSetValidatorStatus(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() // After setting status of the 1st validator, we should be able to get it back. - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) - vs = k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestActivateValidatorOK(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() ctx = ctx.WithBlockTime(now) - err := k.Activate(ctx, testapp.Validators[0].ValAddress) + err := k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) - vs = k.GetValidatorStatus(ctx, testapp.Validators[1].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[1].ValAddress) require.Equal(t, types.NewValidatorStatus(false, time.Time{}), vs) } func TestFailActivateAlreadyActive(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() ctx = ctx.WithBlockTime(now) - err := k.Activate(ctx, testapp.Validators[0].ValAddress) + err := k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.NoError(t, err) - err = k.Activate(ctx, testapp.Validators[0].ValAddress) + err = k.Activate(ctx, bandtesting.Validators[0].ValAddress) require.ErrorIs(t, err, types.ErrValidatorAlreadyActive) } func TestFailActivateTooSoon(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() // Set validator to be inactive just now. - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) // You can't activate until it's been at least InactivePenaltyDuration nanosec. penaltyDuration := k.GetParams(ctx).InactivePenaltyDuration require.ErrorIs( t, - k.Activate(ctx.WithBlockTime(now), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now), bandtesting.Validators[0].ValAddress), types.ErrTooSoonToActivate, ) require.ErrorIs( t, - k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration/2))), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration/2))), bandtesting.Validators[0].ValAddress), types.ErrTooSoonToActivate, ) // So far there must be no changes to the validator's status. - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, now), vs) // Now the time has come. require.NoError( t, - k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration))), testapp.Validators[0].ValAddress), + k.Activate(ctx.WithBlockTime(now.Add(time.Duration(penaltyDuration))), bandtesting.Validators[0].ValAddress), ) - vs = k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + vs = k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now.Add(time.Duration(penaltyDuration))), vs) } func TestMissReportSuccess(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() next := now.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - k.MissReport(ctx.WithBlockTime(next), testapp.Validators[0].ValAddress, next) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + k.MissReport(ctx.WithBlockTime(next), bandtesting.Validators[0].ValAddress, next) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, next), vs) } func TestMissReportTooSoonNoop(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + prev := time.Now().UTC() now := prev.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) - k.MissReport(ctx.WithBlockTime(prev), testapp.Validators[0].ValAddress, prev) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(true, now)) + k.MissReport(ctx.WithBlockTime(prev), bandtesting.Validators[0].ValAddress, prev) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(true, now), vs) } func TestMissReportAlreadyInactiveNoop(t *testing.T) { - _, ctx, k := testapp.CreateTestInput(false) + app, ctx := bandtesting.CreateTestApp(t, false) + k := app.OracleKeeper + now := time.Now().UTC() next := now.Add(time.Duration(10)) - k.SetValidatorStatus(ctx, testapp.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) - k.MissReport(ctx.WithBlockTime(next), testapp.Validators[0].ValAddress, next) - vs := k.GetValidatorStatus(ctx, testapp.Validators[0].ValAddress) + k.SetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress, types.NewValidatorStatus(false, now)) + k.MissReport(ctx.WithBlockTime(next), bandtesting.Validators[0].ValAddress, next) + vs := k.GetValidatorStatus(ctx, bandtesting.Validators[0].ValAddress) require.Equal(t, types.NewValidatorStatus(false, now), vs) }