From a31587486273f053431dfa346ce9728dae4a516e Mon Sep 17 00:00:00 2001 From: DaevMithran Date: Mon, 28 Nov 2022 17:48:43 +0530 Subject: [PATCH 1/5] feat: Migrate fee_tests.go --- ante/fee_test.go | 386 ----------------- ante/tests/fee_test.go | 393 ++++++++++++++++++ ante/{testutil_test.go => tests/setup.go} | 33 +- .../setup_fee_test.go} | 2 +- ante/tests/tests_suite_test.go | 13 + simapp/test_simapp.go | 358 ++++++++++++++++ 6 files changed, 784 insertions(+), 401 deletions(-) delete mode 100644 ante/fee_test.go create mode 100644 ante/tests/fee_test.go rename ante/{testutil_test.go => tests/setup.go} (94%) rename ante/{testdata_test.go => tests/setup_fee_test.go} (98%) create mode 100644 ante/tests/tests_suite_test.go create mode 100644 simapp/test_simapp.go diff --git a/ante/fee_test.go b/ante/fee_test.go deleted file mode 100644 index eb62e4ab9..000000000 --- a/ante/fee_test.go +++ /dev/null @@ -1,386 +0,0 @@ -package ante_test - -import ( - cheqdante "github.com/cheqd/cheqd-node/ante" - cheqdpost "github.com/cheqd/cheqd-node/post" - didtypes "github.com/cheqd/cheqd-node/x/did/types" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/testutil/testdata" - sdk "github.com/cosmos/cosmos-sdk/types" - "github.com/cosmos/cosmos-sdk/types/query" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - "github.com/cosmos/cosmos-sdk/x/bank/testutil" -) - -func (s *AnteTestSuite) TestEnsureZeroMempoolFeesOnSimulationCheckTx() { - s.SetupTest(true) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) - antehandler := sdk.ChainAnteDecorators(mfd) - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(300000000000))) - err := testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) - s.Require().NoError(err) - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - - // set zero gas - s.txBuilder.SetGasLimit(0) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // Set IsCheckTx to true - s.ctx = s.ctx.WithIsCheckTx(true) - - _, err = antehandler(s.ctx, tx, false) - s.Require().Error(err) - - // zero gas is accepted in simulation mode - _, err = antehandler(s.ctx, tx, true) - s.Require().NoError(err) -} - -func (s *AnteTestSuite) TestEnsureMempoolFeesOnCheckTx() { - s.SetupTest(true) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) - antehandler := sdk.ChainAnteDecorators(mfd) - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(300_000_000_000))) - err := testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) - s.Require().NoError(err) - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - feeAmount := NewTestFeeAmount() - gasLimit := uint64(15) - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - s.txBuilder.SetFeeAmount(feeAmount) - s.txBuilder.SetGasLimit(gasLimit) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // Set high gas price so standard test fee fails - ncheqPrice := sdk.NewDecCoinFromDec(didtypes.BaseMinimalDenom, sdk.NewDec(20_000_000_000)) - highGasPrice := []sdk.DecCoin{ncheqPrice} - s.ctx = s.ctx.WithMinGasPrices(highGasPrice) - - // Set IsCheckTx to true - s.ctx = s.ctx.WithIsCheckTx(true) - - // antehandler errors with insufficient fees - _, err = antehandler(s.ctx, tx, false) - s.Require().NotNil(err, "Decorator should have errored on too low fee for local gasPrice") - - // antehandler should not error since we do not check minGasPrice in simulation mode - cacheCtx, _ := s.ctx.CacheContext() - _, err = antehandler(cacheCtx, tx, true) - s.Require().Nil(err, "Decorator should not have errored in simulation mode") - - // Set IsCheckTx to false - s.ctx = s.ctx.WithIsCheckTx(false) - - // antehandler should not error since we do not check minGasPrice in DeliverTx - _, err = antehandler(s.ctx, tx, false) - s.Require().Nil(err, "MempoolFeeDecorator returned error in DeliverTx") - - // Set IsCheckTx back to true for testing sufficient mempool fee - s.ctx = s.ctx.WithIsCheckTx(true) - - ncheqPrice = sdk.NewDecCoinFromDec(didtypes.BaseMinimalDenom, sdk.NewDec(0).Quo(sdk.NewDec(didtypes.BaseFactor))) - lowGasPrice := []sdk.DecCoin{ncheqPrice} - s.ctx = s.ctx.WithMinGasPrices(lowGasPrice) // 1 ncheq - - newCtx, err := antehandler(s.ctx, tx, false) - s.Require().Nil(err, "Decorator should not have errored on fee higher than local gasPrice") - // Priority is the smallest gas price amount in any denom. Since we have only 1 gas price - // of 10000000000ncheq, the priority here is 10*10^9. - s.Require().Equal(int64(10)*didtypes.BaseFactor, newCtx.Priority()) -} - -func (s *AnteTestSuite) TestDeductFeesOnDeliverTx() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - feeAmount := NewTestFeeAmount() - gasLimit := testdata.NewTestGasLimit() - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - s.txBuilder.SetFeeAmount(feeAmount) - s.txBuilder.SetGasLimit(gasLimit) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // Set account with insufficient funds - acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) - s.app.AccountKeeper.SetAccount(s.ctx, acc) - coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(10_000_000_000))) - //nocheck:errcheck - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) - s.Require().NoError(err) - - dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) - antehandler := sdk.ChainAnteDecorators(dfd) - - _, err = antehandler(s.ctx, tx, false) - - s.Require().NotNil(err, "Tx did not error when fee payer had insufficient funds") - - // Set account with sufficient funds - s.app.AccountKeeper.SetAccount(s.ctx, acc) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(200_000_000_000)))) - s.Require().NoError(err) - - _, err = antehandler(s.ctx, tx, false) - - s.Require().Nil(err, "Tx errored after account has been set with sufficient funds") -} - -func (s *AnteTestSuite) TestTaxableTxMempoolInclusionOnCheckTx() { - s.SetupTest(true) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - - // msg and signatures - msg := SandboxDidDoc() - feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) - gasLimit := testdata.NewTestGasLimit() - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - s.txBuilder.SetFeeAmount(feeAmount) - s.txBuilder.SetGasLimit(gasLimit) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // set account with sufficient funds - acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) - s.app.AccountKeeper.SetAccount(s.ctx, acc) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100_000_000_000)))) - s.Require().NoError(err) - - dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) - antehandler := sdk.ChainAnteDecorators(dfd) - - _, err = antehandler(s.ctx, tx, false) - - s.Require().Nil(err, "Tx errored when taxable on checkTx") - - // set checkTx to false - s.ctx = s.ctx.WithIsCheckTx(false) - - // antehandler should not error to replay in mempool or deliverTx - _, err = antehandler(s.ctx, tx, false) - - s.Require().Nil(err, "Tx errored when taxable on deliverTx") -} - -func (s *AnteTestSuite) TestTaxableTxLifecycleOnDeliverTx() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - - // msg and signatures - msg := SandboxDidDoc() - feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) - gasLimit := testdata.NewTestGasLimit() - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - s.txBuilder.SetFeeAmount(feeAmount) - s.txBuilder.SetGasLimit(gasLimit) - s.txBuilder.SetFeePayer(addr1) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // set account with sufficient funds - acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) - s.app.AccountKeeper.SetAccount(s.ctx, acc) - amount := sdk.NewInt(100_000_000_000) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) - s.Require().NoError(err) - - dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) - antehandler := sdk.ChainAnteDecorators(dfd) - - taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) - posthandler := sdk.ChainAnteDecorators(taxDecorator) - - // get supply before tx - supplyBeforeDeflation, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // antehandler should not error to replay in mempool or deliverTx - _, err = antehandler(s.ctx, tx, false) - s.Require().Nil(err, "Tx errored when taxable on deliverTx") - - _, err = posthandler(s.ctx, tx, false) - s.Require().Nil(err, "Tx errored when fee payer had sufficient funds and provided sufficient fee while subtracting tax on deliverTx") - - // get fee params - feeParams := s.app.DidKeeper.GetParams(s.ctx) - - // check balance of fee payer - balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) - createDidTax := feeParams.TxTypes[didtypes.DefaultKeyCreateDid] - s.Require().Equal(amount.Sub(sdk.NewInt(createDidTax.Amount.Int64())), balance.Amount, "Tax was not subtracted from the fee payer") - - // get supply after tx - supplyAfterDeflation, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // check that supply was deflated - burnt := cheqdante.GetBurnFeePortion(feeParams.BurnFactor, sdk.NewCoins(createDidTax)) - s.Require().Equal(supplyBeforeDeflation.Sub(supplyAfterDeflation...), burnt, "Supply was not deflated") - - // check that reward has been sent to the fee collector - reward := cheqdante.GetRewardPortion(sdk.NewCoins(createDidTax), burnt) - feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) - feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) - - s.Require().Equal(feeCollectorBalance.Amount, reward.AmountOf(didtypes.BaseMinimalDenom), "Reward was not sent to the fee collector") -} - -func (s *AnteTestSuite) TestNonTaxableTxLifecycleOnDeliverTx() { - s.SetupTest(false) // setup for DeliverTx - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - feeAmount := NewTestFeeAmount() - gasLimit := testdata.NewTestGasLimit() - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - s.txBuilder.SetFeeAmount(feeAmount) - s.txBuilder.SetGasLimit(gasLimit) - s.txBuilder.SetFeePayer(addr1) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // set account with sufficient funds - acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) - s.app.AccountKeeper.SetAccount(s.ctx, acc) - amount := sdk.NewInt(300_000_000_000) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) - s.Require().NoError(err) - - dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) - antehandler := sdk.ChainAnteDecorators(dfd) - - taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) - posthandler := sdk.ChainAnteDecorators(taxDecorator) - - // get supply before tx - supplyBefore, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // antehandler should not error since we make sure that the fee is sufficient in DeliverTx (simulate=false only, Posthandler will check it otherwise) - _, err = antehandler(s.ctx, tx, false) - s.Require().Nil(err, "Tx errored when non-taxable on deliverTx") - - _, err = posthandler(s.ctx, tx, false) - s.Require().Nil(err, "Tx errored when non-taxable on deliverTx from posthandler") - - // check balance of fee payer - balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) - s.Require().Equal(amount.Sub(sdk.NewInt(feeAmount.AmountOf(didtypes.BaseMinimalDenom).Int64())), balance.Amount, "Fee amount subtracted was not equal to fee amount required for non-taxable tx") - - // get supply after tx - supplyAfter, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // check that supply was not deflated - s.Require().Equal(supplyBefore, supplyAfter, "Supply was deflated") - - // check that reward has been sent to the fee collector - feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) - feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) - - s.Require().Equal(feeCollectorBalance.Amount, feeAmount.AmountOf(didtypes.BaseMinimalDenom), "Fee was not sent to the fee collector") -} - -func (s *AnteTestSuite) TestTaxableTxLifecycleOnDeliverTxSimulation() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - - // keys and addresses - priv1, _, addr1 := testdata.KeyTestPubAddr() - - // msg and signatures - msg := testdata.NewTestMsg(addr1) - s.Require().NoError(s.txBuilder.SetMsgs(msg)) - - // set zero gas - s.txBuilder.SetGasLimit(0) - - privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} - tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) - s.Require().NoError(err) - - // set account with sufficient funds - acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) - s.app.AccountKeeper.SetAccount(s.ctx, acc) - amount := sdk.NewInt(100_000_000_000) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) - s.Require().NoError(err) - - dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) - antehandler := sdk.ChainAnteDecorators(dfd) - - taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) - posthandler := sdk.ChainAnteDecorators(taxDecorator) - - // get supply before tx - supplyBefore, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // antehandler should not error since we make sure that the fee is sufficient in DeliverTx (simulate=false only, Posthandler will check it otherwise) - _, err = antehandler(s.ctx, tx, true) - s.Require().Nil(err, "Tx errored when taxable on deliverTx simulation mode") - - _, err = posthandler(s.ctx, tx, true) - s.Require().Nil(err, "Tx errored when fee payer had sufficient funds and provided sufficient fee while skipping tax simulation mode") - - // check balance of fee payer - balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) - s.Require().Equal(amount, balance.Amount, "Tax was subtracted from fee payer when taxable tx was simulated") - - // get supply after tx - supplyAfter, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) - s.Require().NoError(err) - - // check that supply was not deflated - s.Require().Equal(supplyBefore, supplyAfter, "Supply was deflated when taxable tx simulation mode") - - // check that no fee has been sent to the fee collector - feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) - feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) - - s.Require().Equal(feeCollectorBalance.Amount, sdk.NewInt(0), "Reward was sent to the fee collector when taxable tx simulation mode") -} diff --git a/ante/tests/fee_test.go b/ante/tests/fee_test.go new file mode 100644 index 000000000..0e9264917 --- /dev/null +++ b/ante/tests/fee_test.go @@ -0,0 +1,393 @@ +package ante_tests + +import ( + cheqdante "github.com/cheqd/cheqd-node/ante" + cheqdpost "github.com/cheqd/cheqd-node/post" + didtypes "github.com/cheqd/cheqd-node/x/did/types" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/testutil/testdata" + sdk "github.com/cosmos/cosmos-sdk/types" + "github.com/cosmos/cosmos-sdk/types/query" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + "github.com/cosmos/cosmos-sdk/x/bank/testutil" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +var _ = Describe("Fee tests", func() { + s := new(AnteTestSuite) + + It("Test Ensure Zero Mempool Fees On Simulation CheckTx", func() { + s.SetupTest(true) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) + antehandler := sdk.ChainAnteDecorators(mfd) + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(300000000000))) + err := testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) + Expect(err).To(BeNil()) + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + + // set zero gas + s.txBuilder.SetGasLimit(0) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // Set IsCheckTx to true + s.ctx = s.ctx.WithIsCheckTx(true) + + _, err = antehandler(s.ctx, tx, false) + Expect(err).NotTo(BeNil()) + + // zero gas is accepted in simulation mode + _, err = antehandler(s.ctx, tx, true) + Expect(err).To(BeNil()) + }) + + It("Test Ensure Mempool Fees On CheckTx", func() { + s.SetupTest(true) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) + antehandler := sdk.ChainAnteDecorators(mfd) + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(300_000_000_000))) + err := testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) + Expect(err).To(BeNil()) + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + feeAmount := NewTestFeeAmount() + gasLimit := uint64(15) + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + s.txBuilder.SetFeeAmount(feeAmount) + s.txBuilder.SetGasLimit(gasLimit) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // Set high gas price so standard test fee fails + ncheqPrice := sdk.NewDecCoinFromDec(didtypes.BaseMinimalDenom, sdk.NewDec(20_000_000_000)) + highGasPrice := []sdk.DecCoin{ncheqPrice} + s.ctx = s.ctx.WithMinGasPrices(highGasPrice) + + // Set IsCheckTx to true + s.ctx = s.ctx.WithIsCheckTx(true) + + // antehandler errors with insufficient fees + _, err = antehandler(s.ctx, tx, false) + Expect(err).NotTo(BeNil(), "Decorator should have errored on too low fee for local gasPrice") + + // antehandler should not error since we do not check minGasPrice in simulation mode + cacheCtx, _ := s.ctx.CacheContext() + _, err = antehandler(cacheCtx, tx, true) + Expect(err).To(BeNil(), "Decorator should not have errored in simulation mode") + + // Set IsCheckTx to false + s.ctx = s.ctx.WithIsCheckTx(false) + + // antehandler should not error since we do not check minGasPrice in DeliverTx + _, err = antehandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "MempoolFeeDecorator returned error in DeliverTx") + + // Set IsCheckTx back to true for testing sufficient mempool fee + s.ctx = s.ctx.WithIsCheckTx(true) + + ncheqPrice = sdk.NewDecCoinFromDec(didtypes.BaseMinimalDenom, sdk.NewDec(0).Quo(sdk.NewDec(didtypes.BaseFactor))) + lowGasPrice := []sdk.DecCoin{ncheqPrice} + s.ctx = s.ctx.WithMinGasPrices(lowGasPrice) // 1 ncheq + + newCtx, err := antehandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "Decorator should not have errored on fee higher than local gasPrice") + // Priority is the smallest gas price amount in any denom. Since we have only 1 gas price + // of 10000000000ncheq, the priority here is 10*10^9. + Expect(int64(10) * didtypes.BaseFactor).To(Equal(newCtx.Priority())) + }) + + It("Test Deduct Fees On Deliver Tx", func() { + s.SetupTest(false) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + feeAmount := NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + s.txBuilder.SetFeeAmount(feeAmount) + s.txBuilder.SetGasLimit(gasLimit) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // Set account with insufficient funds + acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) + s.app.AccountKeeper.SetAccount(s.ctx, acc) + coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(10_000_000_000))) + //nocheck:errcheck + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) + Expect(err).To(BeNil()) + + dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + _, err = antehandler(s.ctx, tx, false) + + Expect(err).NotTo(BeNil(), "Tx did not error when fee payer had insufficient funds") + + // Set account with sufficient funds + s.app.AccountKeeper.SetAccount(s.ctx, acc) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(200_000_000_000)))) + Expect(err).To(BeNil()) + + _, err = antehandler(s.ctx, tx, false) + + Expect(err).To(BeNil(), "Tx errored after account has been set with sufficient funds") + }) + + It("Test TaxableTx Mempool Inclusion On CheckTx", func() { + s.SetupTest(true) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := SandboxDidDoc() + feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) + gasLimit := testdata.NewTestGasLimit() + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + s.txBuilder.SetFeeAmount(feeAmount) + s.txBuilder.SetGasLimit(gasLimit) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // set account with sufficient funds + acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) + s.app.AccountKeeper.SetAccount(s.ctx, acc) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100_000_000_000)))) + Expect(err).To(BeNil()) + + dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + _, err = antehandler(s.ctx, tx, false) + + Expect(err).To(BeNil(), "Tx errored when taxable on checkTx") + + // set checkTx to false + s.ctx = s.ctx.WithIsCheckTx(false) + + // antehandler should not error to replay in mempool or deliverTx + _, err = antehandler(s.ctx, tx, false) + + Expect(err).To(BeNil(), "Tx errored when taxable on deliverTx") + }) + + It("Test TaxableTx Lifecycle On DeliverTx", func() { + s.SetupTest(false) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := SandboxDidDoc() + feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) + gasLimit := testdata.NewTestGasLimit() + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + s.txBuilder.SetFeeAmount(feeAmount) + s.txBuilder.SetGasLimit(gasLimit) + s.txBuilder.SetFeePayer(addr1) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // set account with sufficient funds + acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) + s.app.AccountKeeper.SetAccount(s.ctx, acc) + amount := sdk.NewInt(100_000_000_000) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) + Expect(err).To(BeNil()) + + dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) + posthandler := sdk.ChainAnteDecorators(taxDecorator) + + // get supply before tx + supplyBeforeDeflation, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // antehandler should not error to replay in mempool or deliverTx + _, err = antehandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "Tx errored when taxable on deliverTx") + + _, err = posthandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "Tx errored when fee payer had sufficient funds and provided sufficient fee while subtracting tax on deliverTx") + + // get fee params + feeParams := s.app.DidKeeper.GetParams(s.ctx) + + // check balance of fee payer + balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) + createDidTax := feeParams.TxTypes[didtypes.DefaultKeyCreateDid] + Expect(amount.Sub(sdk.NewInt(createDidTax.Amount.Int64()))).To(Equal(balance.Amount), "Tax was not subtracted from the fee payer") + + // get supply after tx + supplyAfterDeflation, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // check that supply was deflated + burnt := cheqdante.GetBurnFeePortion(feeParams.BurnFactor, sdk.NewCoins(createDidTax)) + Expect(supplyBeforeDeflation.Sub(supplyAfterDeflation...)).To(Equal(burnt), "Supply was not deflated") + + // check that reward has been sent to the fee collector + reward := cheqdante.GetRewardPortion(sdk.NewCoins(createDidTax), burnt) + feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) + feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) + + Expect(feeCollectorBalance.Amount).To(Equal(reward.AmountOf(didtypes.BaseMinimalDenom)), "Reward was not sent to the fee collector") + }) + + It("Test Non TaxableTx Lifecycle on DeliverTx", func() { + s.SetupTest(false) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + feeAmount := NewTestFeeAmount() + gasLimit := testdata.NewTestGasLimit() + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + s.txBuilder.SetFeeAmount(feeAmount) + s.txBuilder.SetGasLimit(gasLimit) + s.txBuilder.SetFeePayer(addr1) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // set account with sufficient funds + acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) + s.app.AccountKeeper.SetAccount(s.ctx, acc) + amount := sdk.NewInt(300_000_000_000) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) + Expect(err).To(BeNil()) + + dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) + posthandler := sdk.ChainAnteDecorators(taxDecorator) + + // get supply before tx + supplyBefore, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // antehandler should not error since we make sure that the fee is sufficient in DeliverTx (simulate=false only, Posthandler will check it otherwise) + _, err = antehandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "Tx errored when non-taxable on deliverTx") + + _, err = posthandler(s.ctx, tx, false) + Expect(err).To(BeNil(), "Tx errored when non-taxable on deliverTx from posthandler") + + // check balance of fee payer + balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) + Expect(amount.Sub(sdk.NewInt(feeAmount.AmountOf(didtypes.BaseMinimalDenom).Int64()))).To(Equal(balance.Amount), "Fee amount subtracted was not equal to fee amount required for non-taxable tx") + + // get supply after tx + supplyAfter, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // check that supply was not deflated + Expect(supplyBefore).To(Equal(supplyAfter), "Supply was deflated") + + // check that reward has been sent to the fee collector + feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) + feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) + + Expect(feeCollectorBalance.Amount).To(Equal(feeAmount.AmountOf(didtypes.BaseMinimalDenom)), "Fee was not sent to the fee collector") + }) + + It("Test TaxableTx Lifecycle on DeliveTx Simulation", func() { + s.SetupTest(false) // setup + s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + + // keys and addresses + priv1, _, addr1 := testdata.KeyTestPubAddr() + + // msg and signatures + msg := testdata.NewTestMsg(addr1) + Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) + + // set zero gas + s.txBuilder.SetGasLimit(0) + + privs, accNums, accSeqs := []cryptotypes.PrivKey{priv1}, []uint64{0}, []uint64{0} + tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) + Expect(err).To(BeNil()) + + // set account with sufficient funds + acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) + s.app.AccountKeeper.SetAccount(s.ctx, acc) + amount := sdk.NewInt(100_000_000_000) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, amount))) + Expect(err).To(BeNil()) + + dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) + antehandler := sdk.ChainAnteDecorators(dfd) + + taxDecorator := cheqdpost.NewTaxDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, s.app.DidKeeper, s.app.ResourceKeeper) + posthandler := sdk.ChainAnteDecorators(taxDecorator) + + // get supply before tx + supplyBefore, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // antehandler should not error since we make sure that the fee is sufficient in DeliverTx (simulate=false only, Posthandler will check it otherwise) + _, err = antehandler(s.ctx, tx, true) + Expect(err).To(BeNil(), "Tx errored when taxable on deliverTx simulation mode") + + _, err = posthandler(s.ctx, tx, true) + Expect(err).To(BeNil(), "Tx errored when fee payer had sufficient funds and provided sufficient fee while skipping tax simulation mode") + + // check balance of fee payer + balance := s.app.BankKeeper.GetBalance(s.ctx, addr1, didtypes.BaseMinimalDenom) + Expect(amount).To(Equal(balance.Amount), "Tax was subtracted from fee payer when taxable tx was simulated") + + // get supply after tx + supplyAfter, _, err := s.app.BankKeeper.GetPaginatedTotalSupply(s.ctx, &query.PageRequest{}) + Expect(err).To(BeNil()) + + // check that supply was not deflated + Expect(supplyBefore).To(Equal(supplyAfter), "Supply was deflated when taxable tx simulation mode") + + // check that no fee has been sent to the fee collector + feeCollector := s.app.AccountKeeper.GetModuleAddress(authtypes.FeeCollectorName) + feeCollectorBalance := s.app.BankKeeper.GetBalance(s.ctx, feeCollector, didtypes.BaseMinimalDenom) + + Expect(feeCollectorBalance.Amount).To(Equal(sdk.NewInt(0)), "Reward was sent to the fee collector when taxable tx simulation mode") + }) +}) diff --git a/ante/testutil_test.go b/ante/tests/setup.go similarity index 94% rename from ante/testutil_test.go rename to ante/tests/setup.go index 478219e39..ccfd68fd8 100644 --- a/ante/testutil_test.go +++ b/ante/tests/setup.go @@ -1,9 +1,8 @@ -package ante_test +package ante_tests import ( "errors" "fmt" - "testing" "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -43,8 +42,8 @@ type AnteTestSuite struct { } // returns context and app with params set on account keeper -func createTestApp(t *testing.T, isCheckTx bool) (*simapp.SimApp, sdk.Context) { - app := simapp.Setup(t, isCheckTx) +func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { + app := simapp.SetupForGinkgo(isCheckTx) ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) @@ -57,15 +56,14 @@ func createTestApp(t *testing.T, isCheckTx bool) (*simapp.SimApp, sdk.Context) { return app, ctx } -func TestAnteTestSuite(t *testing.T) { - suite.Run(t, new(AnteTestSuite)) -} +// func TestAnteTestSuite(t *testing.T) { +// suite.Run(t, new(AnteTestSuite)) +// } // SetupTest setups a new test, with new app, context, and anteHandler. func (s *AnteTestSuite) SetupTest(isCheckTx bool) { - s.app, s.ctx = createTestApp(s.T(), isCheckTx) + s.app, s.ctx = createTestApp(isCheckTx) s.ctx = s.ctx.WithBlockHeight(1) - // Set up TxConfig. encodingConfig := cheqdapp.MakeTestEncodingConfig() // We're using TestMsg encoding in some tests, so register it here. @@ -86,8 +84,9 @@ func (s *AnteTestSuite) SetupTest(isCheckTx bool) { SigGasConsumer: sdkante.DefaultSigVerificationGasConsumer, }, ) - - s.Require().NoError(err) + if err != nil { + panic(err) + } s.anteHandler = anteHandler } @@ -100,16 +99,22 @@ func (s *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { priv, _, addr := testdata.KeyTestPubAddr() acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr) err := acc.SetAccountNumber(uint64(i)) - s.Require().NoError(err) + if err != nil { + panic(err) + } s.app.AccountKeeper.SetAccount(s.ctx, acc) someCoins := sdk.Coins{ sdk.NewInt64Coin("ncheq", 1000000*1e9), // 1mn CHEQ } err = s.app.BankKeeper.MintCoins(s.ctx, minttypes.ModuleName, someCoins) - s.Require().NoError(err) + if err != nil { + panic(err) + } err = s.app.BankKeeper.SendCoinsFromModuleToAccount(s.ctx, minttypes.ModuleName, addr, someCoins) - s.Require().NoError(err) + if err != nil { + panic(err) + } accounts = append(accounts, TestAccount{acc, priv}) } diff --git a/ante/testdata_test.go b/ante/tests/setup_fee_test.go similarity index 98% rename from ante/testdata_test.go rename to ante/tests/setup_fee_test.go index 7e965cccd..b67de6ea3 100644 --- a/ante/testdata_test.go +++ b/ante/tests/setup_fee_test.go @@ -1,4 +1,4 @@ -package ante_test +package ante_tests import ( "crypto/ed25519" diff --git a/ante/tests/tests_suite_test.go b/ante/tests/tests_suite_test.go new file mode 100644 index 000000000..22a266ec7 --- /dev/null +++ b/ante/tests/tests_suite_test.go @@ -0,0 +1,13 @@ +package ante_tests + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestTests(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Tests Suite") +} diff --git a/simapp/test_simapp.go b/simapp/test_simapp.go new file mode 100644 index 000000000..218357adf --- /dev/null +++ b/simapp/test_simapp.go @@ -0,0 +1,358 @@ +package simapp + +import ( + "encoding/json" + "math/rand" + "reflect" + "time" + + abci "github.com/tendermint/tendermint/abci/types" + tmjson "github.com/tendermint/tendermint/libs/json" + tmproto "github.com/tendermint/tendermint/proto/tendermint/types" + tmtypes "github.com/tendermint/tendermint/types" + + bam "github.com/cosmos/cosmos-sdk/baseapp" + "github.com/cosmos/cosmos-sdk/client" + codectypes "github.com/cosmos/cosmos-sdk/codec/types" + cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" + "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" + cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" + "github.com/cosmos/cosmos-sdk/simapp/helpers" + "github.com/cosmos/cosmos-sdk/testutil/mock" + sdk "github.com/cosmos/cosmos-sdk/types" + authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" + banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" + stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" + + // cheqd specific imports + cheqdapp "github.com/cheqd/cheqd-node/app" + didtypes "github.com/cheqd/cheqd-node/x/did/types" + resourcetypes "github.com/cheqd/cheqd-node/x/resource/types" +) + +// NewSimappWithCustomOptions initializes a new SimApp with custom options. +func NewSimappWithCustomOptionsForGinkgo(isCheckTx bool, options SetupOptions) *SimApp { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) + balance := banktypes.Balance{ + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), + } + + app := NewSimApp(options.Logger, options.DB, nil, true, options.SkipUpgradeHeights, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts) + genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) + genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) + + if !isCheckTx { + // init chain must be called to stop deliverState from being nil + stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") + if err != nil { + panic(err) + } + + // Initialize the chain + app.InitChain( + abci.RequestInitChain{ + Validators: []abci.ValidatorUpdate{}, + ConsensusParams: DefaultConsensusParams, + AppStateBytes: stateBytes, + }, + ) + } + + return app +} + +// Setup initializes a new SimApp. A Nop logger is set in SimApp. +func SetupForGinkgo(isCheckTx bool) *SimApp { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) + balance := banktypes.Balance{ + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), + } + + app := SetupWithGenesisValSetForGinkgo(valSet, []authtypes.GenesisAccount{acc}, balance) + + return app +} + +// Setup initializes a new SimApp. A Nop logger is set in SimApp. +func SetupTest(isCheckTx bool) *SimApp { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) + balance := banktypes.Balance{ + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), + } + + app := SetupWithGenesisValSetForGinkgo(valSet, []authtypes.GenesisAccount{acc}, balance) + + return app +} + +func genesisStateWithValSetForGinkgo( + app *SimApp, genesisState cheqdapp.GenesisState, + valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, + balances ...banktypes.Balance, +) cheqdapp.GenesisState { + // set genesis accounts + authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) + genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) + + validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) + delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) + + bondAmt := sdk.DefaultPowerReduction + + for _, val := range valSet.Validators { + pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) + 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: bondAmt, + 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(), + } + validators = append(validators, validator) + delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) + + } + // set validators and delegations + stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) + genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) + + totalSupply := sdk.NewCoins() + for _, b := range balances { + // add genesis acc tokens to total supply + totalSupply = totalSupply.Add(b.Coins...) + } + + for range delegations { + // add delegated tokens to total supply + totalSupply = totalSupply.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)) + } + + // add bonded amount to bonded pool module account + balances = append(balances, banktypes.Balance{ + Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), + Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)}, + }) + + // update total supply + bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}) + genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) + + // set did module genesis state + didGenesis := didtypes.DefaultGenesis() + genesisState[didtypes.ModuleName] = app.AppCodec().MustMarshalJSON(didGenesis) + + // set resource module genesis state + resourceGenesis := resourcetypes.DefaultGenesis() + genesisState[resourcetypes.ModuleName] = app.AppCodec().MustMarshalJSON(resourceGenesis) + + return genesisState +} + +// SetupWithGenesisValSet initializes a new SimApp 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 simapp from first genesis +// account. A Nop logger is set in SimApp. +func SetupWithGenesisValSetForGinkgo(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { + app, genesisState := setup(true, 5) + genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, genAccs, balances...) + + stateBytes, err := json.MarshalIndent(genesisState, "", " ") + if err != nil { + panic(err) + } + + // init chain will set the validator set and initialize the genesis accounts + app.InitChain( + abci.RequestInitChain{ + Validators: []abci.ValidatorUpdate{}, + ConsensusParams: DefaultConsensusParams, + AppStateBytes: stateBytes, + }, + ) + + // commit genesis changes + app.Commit() + app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ + Height: app.LastBlockHeight() + 1, + AppHash: app.LastCommitID().Hash, + ValidatorsHash: valSet.Hash(), + NextValidatorsHash: valSet.Hash(), + }}) + + return app +} + +// SetupWithGenesisAccounts initializes a new SimApp with the provided genesis +// accounts and possible balances. +func SetupWithGenesisAccountsForGinkgo(genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + return SetupWithGenesisValSetForGinkgo(valSet, genAccs, balances...) +} + +// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts +// that also act as delegators. +func GenesisStateWithSingleValidatorForGinkgo(app *SimApp) cheqdapp.GenesisState { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + panic(err) + } + + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) + balances := []banktypes.Balance{ + { + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), + }, + } + + genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) + genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) + + return genesisState +} + +// CheckBalance checks the balance of an account. +func CheckBalanceForGinkgo(app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { + ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) + if reflect.DeepEqual(balances, app.BankKeeper.GetAllBalances(ctxCheck, addr)) { + panic("Invalid balance of account") + } +} + +// SignCheckDeliver checks a generated signed transaction and simulates a +// block commitment with the given transaction. A test assertion is made using +// the parameter 'expPass' against the result. A corresponding result is +// returned. +func SignCheckDeliverForGinkgo( + txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, + chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, +) (sdk.GasInfo, *sdk.Result, error) { + tx, err := helpers.GenSignedMockTx( + rand.New(rand.NewSource(time.Now().UnixNano())), + txCfg, + msgs, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + helpers.DefaultGenTxGas, + chainID, + accNums, + accSeqs, + priv..., + ) + if err != nil { + panic(err) + } + txBytes, err := txCfg.TxEncoder()(tx) + if err != nil { + panic(err) + } + + // Must simulate now as CheckTx doesn't run Msgs anymore + _, res, err := app.Simulate(txBytes) + + if expSimPass { + if err != nil { + panic(err) + } + if res == nil { + panic(err) + } + } else { + if err != nil { + panic(err) + } + if res == nil { + panic(err) + } + } + + // Simulate a sending a transaction and committing a block + app.BeginBlock(abci.RequestBeginBlock{Header: header}) + gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) + + if expPass { + if err != nil { + panic(err) + } + if res == nil { + panic(err) + } + } else { + if err != nil { + panic(err) + } + if res == nil { + panic(err) + } + } + + app.EndBlock(abci.RequestEndBlock{}) + app.Commit() + + return gInfo, res, err +} From db8945dcb4533c31be069090f650e0c6194d7871 Mon Sep 17 00:00:00 2001 From: DaevMithran Date: Tue, 29 Nov 2022 12:42:16 +0530 Subject: [PATCH 2/5] feat: ReStructure ante_test --- ante/{tests/tests_suite_test.go => ante_suite_test.go} | 6 +++--- ante/{tests => }/fee_test.go | 2 +- ante/{tests/setup_fee_test.go => testdata_test.go} | 2 +- ante/{tests/setup.go => testutil_test.go} | 2 +- 4 files changed, 6 insertions(+), 6 deletions(-) rename ante/{tests/tests_suite_test.go => ante_suite_test.go} (59%) rename ante/{tests => }/fee_test.go (99%) rename ante/{tests/setup_fee_test.go => testdata_test.go} (98%) rename ante/{tests/setup.go => testutil_test.go} (99%) diff --git a/ante/tests/tests_suite_test.go b/ante/ante_suite_test.go similarity index 59% rename from ante/tests/tests_suite_test.go rename to ante/ante_suite_test.go index 22a266ec7..ddb74f262 100644 --- a/ante/tests/tests_suite_test.go +++ b/ante/ante_suite_test.go @@ -1,4 +1,4 @@ -package ante_tests +package ante_test import ( "testing" @@ -7,7 +7,7 @@ import ( . "github.com/onsi/gomega" ) -func TestTests(t *testing.T) { +func TestAnte(t *testing.T) { RegisterFailHandler(Fail) - RunSpecs(t, "Tests Suite") + RunSpecs(t, "Ante Suite") } diff --git a/ante/tests/fee_test.go b/ante/fee_test.go similarity index 99% rename from ante/tests/fee_test.go rename to ante/fee_test.go index 0e9264917..aa3fa369a 100644 --- a/ante/tests/fee_test.go +++ b/ante/fee_test.go @@ -1,4 +1,4 @@ -package ante_tests +package ante_test import ( cheqdante "github.com/cheqd/cheqd-node/ante" diff --git a/ante/tests/setup_fee_test.go b/ante/testdata_test.go similarity index 98% rename from ante/tests/setup_fee_test.go rename to ante/testdata_test.go index b67de6ea3..7e965cccd 100644 --- a/ante/tests/setup_fee_test.go +++ b/ante/testdata_test.go @@ -1,4 +1,4 @@ -package ante_tests +package ante_test import ( "crypto/ed25519" diff --git a/ante/tests/setup.go b/ante/testutil_test.go similarity index 99% rename from ante/tests/setup.go rename to ante/testutil_test.go index ccfd68fd8..bf589a95b 100644 --- a/ante/tests/setup.go +++ b/ante/testutil_test.go @@ -1,4 +1,4 @@ -package ante_tests +package ante_test import ( "errors" From a0e056b8883d9f6f5d81f1351f72316955086e83 Mon Sep 17 00:00:00 2001 From: DaevMithran Date: Tue, 29 Nov 2022 15:30:40 +0530 Subject: [PATCH 3/5] fix: Linting errors --- simapp/test_simapp.go | 20 ++++---------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/simapp/test_simapp.go b/simapp/test_simapp.go index 218357adf..3d0853531 100644 --- a/simapp/test_simapp.go +++ b/simapp/test_simapp.go @@ -316,17 +316,11 @@ func SignCheckDeliverForGinkgo( _, res, err := app.Simulate(txBytes) if expSimPass { - if err != nil { - panic(err) - } - if res == nil { + if err != nil || res == nil { panic(err) } } else { - if err != nil { - panic(err) - } - if res == nil { + if err == nil || res != nil { panic(err) } } @@ -336,17 +330,11 @@ func SignCheckDeliverForGinkgo( gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) if expPass { - if err != nil { - panic(err) - } - if res == nil { + if err != nil || res == nil { panic(err) } } else { - if err != nil { - panic(err) - } - if res == nil { + if err == nil || res != nil { panic(err) } } From 5902c83519c5de7f97e2a1851b1a8c00f7502cba Mon Sep 17 00:00:00 2001 From: DaevMithran Date: Wed, 30 Nov 2022 12:12:26 +0530 Subject: [PATCH 4/5] feat: Update error handling --- ante/fee_test.go | 86 ++++++++++++++++++++----------------------- ante/testutil_test.go | 15 ++++---- 2 files changed, 48 insertions(+), 53 deletions(-) diff --git a/ante/fee_test.go b/ante/fee_test.go index aa3fa369a..50e322c2e 100644 --- a/ante/fee_test.go +++ b/ante/fee_test.go @@ -15,13 +15,16 @@ import ( . "github.com/onsi/gomega" ) -var _ = Describe("Fee tests", func() { +var _ = Describe("Fee tests on CheckTx", func() { s := new(AnteTestSuite) - It("Test Ensure Zero Mempool Fees On Simulation CheckTx", func() { - s.SetupTest(true) // setup + BeforeEach(func() { + err := s.SetupTest(true) // setup + Expect(err).To(BeNil(), "Error on creating test app") s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + }) + It("Ensure Zero Mempool Fees On Simulation", func() { mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) antehandler := sdk.ChainAnteDecorators(mfd) @@ -53,10 +56,7 @@ var _ = Describe("Fee tests", func() { Expect(err).To(BeNil()) }) - It("Test Ensure Mempool Fees On CheckTx", func() { - s.SetupTest(true) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - + It("Ensure Mempool Fees", func() { mfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, s.app.FeeGrantKeeper, nil) antehandler := sdk.ChainAnteDecorators(mfd) @@ -116,16 +116,13 @@ var _ = Describe("Fee tests", func() { Expect(int64(10) * didtypes.BaseFactor).To(Equal(newCtx.Priority())) }) - It("Test Deduct Fees On Deliver Tx", func() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - + It("TaxableTx Mempool Inclusion", func() { // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg := testdata.NewTestMsg(addr1) - feeAmount := NewTestFeeAmount() + msg := SandboxDidDoc() + feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) gasLimit := testdata.NewTestGasLimit() Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) s.txBuilder.SetFeeAmount(feeAmount) @@ -135,12 +132,10 @@ var _ = Describe("Fee tests", func() { tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) Expect(err).To(BeNil()) - // Set account with insufficient funds + // set account with sufficient funds acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) s.app.AccountKeeper.SetAccount(s.ctx, acc) - coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(10_000_000_000))) - //nocheck:errcheck - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100_000_000_000)))) Expect(err).To(BeNil()) dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) @@ -148,28 +143,33 @@ var _ = Describe("Fee tests", func() { _, err = antehandler(s.ctx, tx, false) - Expect(err).NotTo(BeNil(), "Tx did not error when fee payer had insufficient funds") + Expect(err).To(BeNil(), "Tx errored when taxable on checkTx") - // Set account with sufficient funds - s.app.AccountKeeper.SetAccount(s.ctx, acc) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(200_000_000_000)))) - Expect(err).To(BeNil()) + // set checkTx to false + s.ctx = s.ctx.WithIsCheckTx(false) + // antehandler should not error to replay in mempool or deliverTx _, err = antehandler(s.ctx, tx, false) - Expect(err).To(BeNil(), "Tx errored after account has been set with sufficient funds") + Expect(err).To(BeNil(), "Tx errored when taxable on deliverTx") }) +}) - It("Test TaxableTx Mempool Inclusion On CheckTx", func() { - s.SetupTest(true) // setup +var _ = Describe("Fee tests on DeliverTx", func() { + s := new(AnteTestSuite) + + BeforeEach(func() { + s.SetupTest(false) // setup s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() + }) + It("Deduct Fees", func() { // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() // msg and signatures - msg := SandboxDidDoc() - feeAmount := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(5_000_000_000))) + msg := testdata.NewTestMsg(addr1) + feeAmount := NewTestFeeAmount() gasLimit := testdata.NewTestGasLimit() Expect(s.txBuilder.SetMsgs(msg)).To(BeNil()) s.txBuilder.SetFeeAmount(feeAmount) @@ -179,10 +179,12 @@ var _ = Describe("Fee tests", func() { tx, err := s.CreateTestTx(privs, accNums, accSeqs, s.ctx.ChainID()) Expect(err).To(BeNil()) - // set account with sufficient funds + // Set account with insufficient funds acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr1) s.app.AccountKeeper.SetAccount(s.ctx, acc) - err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100_000_000_000)))) + coins := sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(10_000_000_000))) + //nocheck:errcheck + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, coins) Expect(err).To(BeNil()) dfd := cheqdante.NewDeductFeeDecorator(s.app.AccountKeeper, s.app.BankKeeper, nil, nil) @@ -190,21 +192,19 @@ var _ = Describe("Fee tests", func() { _, err = antehandler(s.ctx, tx, false) - Expect(err).To(BeNil(), "Tx errored when taxable on checkTx") + Expect(err).NotTo(BeNil(), "Tx did not error when fee payer had insufficient funds") - // set checkTx to false - s.ctx = s.ctx.WithIsCheckTx(false) + // Set account with sufficient funds + s.app.AccountKeeper.SetAccount(s.ctx, acc) + err = testutil.FundAccount(s.app.BankKeeper, s.ctx, addr1, sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(200_000_000_000)))) + Expect(err).To(BeNil()) - // antehandler should not error to replay in mempool or deliverTx _, err = antehandler(s.ctx, tx, false) - Expect(err).To(BeNil(), "Tx errored when taxable on deliverTx") + Expect(err).To(BeNil(), "Tx errored after account has been set with sufficient funds") }) - It("Test TaxableTx Lifecycle On DeliverTx", func() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - + It("TaxableTx Lifecycle", func() { // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() @@ -269,10 +269,7 @@ var _ = Describe("Fee tests", func() { Expect(feeCollectorBalance.Amount).To(Equal(reward.AmountOf(didtypes.BaseMinimalDenom)), "Reward was not sent to the fee collector") }) - It("Test Non TaxableTx Lifecycle on DeliverTx", func() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - + It("Non TaxableTx Lifecycle", func() { // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() @@ -331,10 +328,7 @@ var _ = Describe("Fee tests", func() { Expect(feeCollectorBalance.Amount).To(Equal(feeAmount.AmountOf(didtypes.BaseMinimalDenom)), "Fee was not sent to the fee collector") }) - It("Test TaxableTx Lifecycle on DeliveTx Simulation", func() { - s.SetupTest(false) // setup - s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() - + It("TaxableTx Lifecycle on Simulation", func() { // keys and addresses priv1, _, addr1 := testdata.KeyTestPubAddr() diff --git a/ante/testutil_test.go b/ante/testutil_test.go index bf589a95b..8097f247a 100644 --- a/ante/testutil_test.go +++ b/ante/testutil_test.go @@ -61,7 +61,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { // } // SetupTest setups a new test, with new app, context, and anteHandler. -func (s *AnteTestSuite) SetupTest(isCheckTx bool) { +func (s *AnteTestSuite) SetupTest(isCheckTx bool) error { s.app, s.ctx = createTestApp(isCheckTx) s.ctx = s.ctx.WithBlockHeight(1) // Set up TxConfig. @@ -85,14 +85,15 @@ func (s *AnteTestSuite) SetupTest(isCheckTx bool) { }, ) if err != nil { - panic(err) + return err } s.anteHandler = anteHandler + return nil } // CreateTestAccounts creates `numAccs` accounts, and return all relevant // information about them including their private keys. -func (s *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { +func (s *AnteTestSuite) CreateTestAccounts(numAccs int) ([]TestAccount, error) { var accounts []TestAccount for i := 0; i < numAccs; i++ { @@ -100,7 +101,7 @@ func (s *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { acc := s.app.AccountKeeper.NewAccountWithAddress(s.ctx, addr) err := acc.SetAccountNumber(uint64(i)) if err != nil { - panic(err) + return nil, err } s.app.AccountKeeper.SetAccount(s.ctx, acc) someCoins := sdk.Coins{ @@ -108,18 +109,18 @@ func (s *AnteTestSuite) CreateTestAccounts(numAccs int) []TestAccount { } err = s.app.BankKeeper.MintCoins(s.ctx, minttypes.ModuleName, someCoins) if err != nil { - panic(err) + return nil, err } err = s.app.BankKeeper.SendCoinsFromModuleToAccount(s.ctx, minttypes.ModuleName, addr, someCoins) if err != nil { - panic(err) + return nil, err } accounts = append(accounts, TestAccount{acc, priv}) } - return accounts + return accounts, nil } // CreateTestTx is a helper function to create a tx given multiple inputs. From 67ae6f0c5fd94bf119b40f30bbd0b8eb6f3b051a Mon Sep 17 00:00:00 2001 From: DaevMithran Date: Wed, 30 Nov 2022 15:40:16 +0530 Subject: [PATCH 5/5] feat: Migrate keeper tests to ginkgo --- ante/fee_test.go | 3 +- ante/testutil_test.go | 15 +- simapp/test_helpers.go | 244 +++++++----- simapp/test_simapp.go | 346 ------------------ .../keeper_param_change_proposal_test.go | 150 ++++---- x/did/keeper/keeper_suite_test.go | 13 + .../keeper_param_change_proposal_test.go | 144 ++++---- x/resource/keeper/keeper_suite_test.go | 13 + 8 files changed, 340 insertions(+), 588 deletions(-) delete mode 100644 simapp/test_simapp.go create mode 100644 x/did/keeper/keeper_suite_test.go create mode 100644 x/resource/keeper/keeper_suite_test.go diff --git a/ante/fee_test.go b/ante/fee_test.go index 50e322c2e..617a23da9 100644 --- a/ante/fee_test.go +++ b/ante/fee_test.go @@ -159,7 +159,8 @@ var _ = Describe("Fee tests on DeliverTx", func() { s := new(AnteTestSuite) BeforeEach(func() { - s.SetupTest(false) // setup + err := s.SetupTest(false) // setup + Expect(err).To(BeNil(), "Error on creating test app") s.txBuilder = s.clientCtx.TxConfig.NewTxBuilder() }) diff --git a/ante/testutil_test.go b/ante/testutil_test.go index 8097f247a..1782b687d 100644 --- a/ante/testutil_test.go +++ b/ante/testutil_test.go @@ -42,8 +42,11 @@ type AnteTestSuite struct { } // returns context and app with params set on account keeper -func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { - app := simapp.SetupForGinkgo(isCheckTx) +func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context, error) { + app, err := simapp.Setup(isCheckTx) + if err != nil { + return nil, sdk.Context{}, err + } ctx := app.BaseApp.NewContext(isCheckTx, tmproto.Header{}) app.AccountKeeper.SetParams(ctx, authtypes.DefaultParams()) @@ -53,7 +56,7 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { resourceFeeParams := resourcetypes.DefaultGenesis().FeeParams app.ResourceKeeper.SetParams(ctx, *resourceFeeParams) - return app, ctx + return app, ctx, nil } // func TestAnteTestSuite(t *testing.T) { @@ -62,7 +65,11 @@ func createTestApp(isCheckTx bool) (*simapp.SimApp, sdk.Context) { // SetupTest setups a new test, with new app, context, and anteHandler. func (s *AnteTestSuite) SetupTest(isCheckTx bool) error { - s.app, s.ctx = createTestApp(isCheckTx) + var err error + s.app, s.ctx, err = createTestApp(isCheckTx) + if err != nil { + return err + } s.ctx = s.ctx.WithBlockHeight(1) // Set up TxConfig. encodingConfig := cheqdapp.MakeTestEncodingConfig() diff --git a/simapp/test_helpers.go b/simapp/test_helpers.go index d8ca01666..31488d556 100644 --- a/simapp/test_helpers.go +++ b/simapp/test_helpers.go @@ -6,11 +6,10 @@ import ( "encoding/json" "fmt" "math/rand" + "reflect" "strconv" - "testing" "time" - "github.com/stretchr/testify/require" abci "github.com/tendermint/tendermint/abci/types" tmjson "github.com/tendermint/tendermint/libs/json" "github.com/tendermint/tendermint/libs/log" @@ -85,12 +84,12 @@ func setup(withGenesis bool, invCheckPeriod uint) (*SimApp, cheqdapp.GenesisStat } // NewSimappWithCustomOptions initializes a new SimApp with custom options. -func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptions) *SimApp { - t.Helper() - +func NewSimappWithCustomOptions(isCheckTx bool, options SetupOptions) (*SimApp, error) { privVal := mock.NewPV() pubKey, err := privVal.GetPubKey() - require.NoError(t, err) + if err != nil { + return nil, err + } // create validator set with single validator validator := tmtypes.NewValidator(pubKey, 1) valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) @@ -105,12 +104,17 @@ func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptio app := NewSimApp(options.Logger, options.DB, nil, true, options.SkipUpgradeHeights, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts) genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) - genesisState = genesisStateWithValSet(t, app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) + genesisState, err = genesisStateWithValSet(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) + if err != nil { + return nil, err + } if !isCheckTx { // init chain must be called to stop deliverState from being nil stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") - require.NoError(t, err) + if err != nil { + return nil, err + } // Initialize the chain app.InitChain( @@ -122,16 +126,16 @@ func NewSimappWithCustomOptions(t *testing.T, isCheckTx bool, options SetupOptio ) } - return app + return app, nil } // Setup initializes a new SimApp. A Nop logger is set in SimApp. -func Setup(t *testing.T, isCheckTx bool) *SimApp { - t.Helper() - +func Setup(isCheckTx bool) (*SimApp, error) { privVal := mock.NewPV() pubKey, err := privVal.GetPubKey() - require.NoError(t, err) + if err != nil { + return nil, err + } // create validator set with single validator validator := tmtypes.NewValidator(pubKey, 1) @@ -145,16 +149,46 @@ func Setup(t *testing.T, isCheckTx bool) *SimApp { Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), } - app := SetupWithGenesisValSet(t, valSet, []authtypes.GenesisAccount{acc}, balance) + app, err := SetupWithGenesisValSet(valSet, []authtypes.GenesisAccount{acc}, balance) + if err != nil { + return nil, err + } - return app + return app, nil } -func genesisStateWithValSet(t *testing.T, +// Setup initializes a new SimApp. A Nop logger is set in SimApp. +func SetupTest(isCheckTx bool) (*SimApp, error) { + privVal := mock.NewPV() + pubKey, err := privVal.GetPubKey() + if err != nil { + return nil, err + } + // create validator set with single validator + validator := tmtypes.NewValidator(pubKey, 1) + valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) + + // generate genesis account + senderPrivKey := secp256k1.GenPrivKey() + acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) + balance := banktypes.Balance{ + Address: acc.GetAddress().String(), + Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), + } + + app, err := SetupWithGenesisValSet(valSet, []authtypes.GenesisAccount{acc}, balance) + if err != nil { + return nil, err + } + + return app, nil +} + +func genesisStateWithValSet( app *SimApp, genesisState cheqdapp.GenesisState, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance, -) cheqdapp.GenesisState { +) (cheqdapp.GenesisState, error) { // set genesis accounts authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) @@ -166,9 +200,13 @@ func genesisStateWithValSet(t *testing.T, for _, val := range valSet.Validators { pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - require.NoError(t, err) + if err != nil { + return nil, err + } pkAny, err := codectypes.NewAnyWithValue(pk) - require.NoError(t, err) + if err != nil { + return nil, err + } validator := stakingtypes.Validator{ OperatorAddress: sdk.ValAddress(val.Address).String(), ConsensusPubkey: pkAny, @@ -219,21 +257,24 @@ func genesisStateWithValSet(t *testing.T, resourceGenesis := resourcetypes.DefaultGenesis() genesisState[resourcetypes.ModuleName] = app.AppCodec().MustMarshalJSON(resourceGenesis) - return genesisState + return genesisState, nil } // SetupWithGenesisValSet initializes a new SimApp 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 simapp from first genesis // account. A Nop logger is set in SimApp. -func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { - t.Helper() - +func SetupWithGenesisValSet(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) (*SimApp, error) { app, genesisState := setup(true, 5) - genesisState = genesisStateWithValSet(t, app, genesisState, valSet, genAccs, balances...) + genesisState, err := genesisStateWithValSet(app, genesisState, valSet, genAccs, balances...) + if err != nil { + return nil, err + } stateBytes, err := json.MarshalIndent(genesisState, "", " ") - require.NoError(t, err) + if err != nil { + return nil, err + } // init chain will set the validator set and initialize the genesis accounts app.InitChain( @@ -253,33 +294,33 @@ func SetupWithGenesisValSet(t *testing.T, valSet *tmtypes.ValidatorSet, genAccs NextValidatorsHash: valSet.Hash(), }}) - return app + return app, nil } // SetupWithGenesisAccounts initializes a new SimApp with the provided genesis // accounts and possible balances. -func SetupWithGenesisAccounts(t *testing.T, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { - t.Helper() - +func SetupWithGenesisAccounts(genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) (*SimApp, error) { privVal := mock.NewPV() pubKey, err := privVal.GetPubKey() - require.NoError(t, err) + if err != nil { + return nil, err + } // create validator set with single validator validator := tmtypes.NewValidator(pubKey, 1) valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - return SetupWithGenesisValSet(t, valSet, genAccs, balances...) + return SetupWithGenesisValSet(valSet, genAccs, balances...) } // GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts // that also act as delegators. -func GenesisStateWithSingleValidator(t *testing.T, app *SimApp) cheqdapp.GenesisState { - t.Helper() - +func GenesisStateWithSingleValidator(app *SimApp) (cheqdapp.GenesisState, error) { privVal := mock.NewPV() pubKey, err := privVal.GetPubKey() - require.NoError(t, err) + if err != nil { + return nil, err + } // create validator set with single validator validator := tmtypes.NewValidator(pubKey, 1) @@ -296,9 +337,80 @@ func GenesisStateWithSingleValidator(t *testing.T, app *SimApp) cheqdapp.Genesis } genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) - genesisState = genesisStateWithValSet(t, app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) + genesisState, err = genesisStateWithValSet(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) + if err != nil { + return nil, err + } + + return genesisState, nil +} - return genesisState +// CheckBalance checks the balance of an account. +func CheckBalance(app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { + ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) + if reflect.DeepEqual(balances, app.BankKeeper.GetAllBalances(ctxCheck, addr)) { + panic("Invalid balance of account") + } +} + +// SignCheckDeliver checks a generated signed transaction and simulates a +// block commitment with the given transaction. A test assertion is made using +// the parameter 'expPass' against the result. A corresponding result is +// returned. +func SignCheckDeliver( + txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, + chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, +) (sdk.GasInfo, *sdk.Result, error) { + tx, err := helpers.GenSignedMockTx( + rand.New(rand.NewSource(time.Now().UnixNano())), + txCfg, + msgs, + sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, + helpers.DefaultGenTxGas, + chainID, + accNums, + accSeqs, + priv..., + ) + if err != nil { + return sdk.GasInfo{}, nil, err + } + txBytes, err := txCfg.TxEncoder()(tx) + if err != nil { + return sdk.GasInfo{}, nil, err + } + + // Must simulate now as CheckTx doesn't run Msgs anymore + _, res, err := app.Simulate(txBytes) + + if expSimPass { + if err != nil || res == nil { + return sdk.GasInfo{}, nil, err + } + } else { + if err == nil || res != nil { + return sdk.GasInfo{}, nil, err + } + } + + // Simulate a sending a transaction and committing a block + app.BeginBlock(abci.RequestBeginBlock{Header: header}) + gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) + + if expPass { + if err != nil || res == nil { + return sdk.GasInfo{}, nil, err + } + } else { + if err == nil || res != nil { + return sdk.GasInfo{}, nil, err + } + } + + app.EndBlock(abci.RequestEndBlock{}) + app.Commit() + + return gInfo, res, err } type GenerateAccountStrategy func(int) []sdk.AccAddress @@ -413,64 +525,6 @@ func TestAddr(addr string, bech string) (sdk.AccAddress, error) { return res, nil } -// CheckBalance checks the balance of an account. -func CheckBalance(t *testing.T, app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { - ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) - require.True(t, balances.IsEqual(app.BankKeeper.GetAllBalances(ctxCheck, addr))) -} - -// SignCheckDeliver checks a generated signed transaction and simulates a -// block commitment with the given transaction. A test assertion is made using -// the parameter 'expPass' against the result. A corresponding result is -// returned. -func SignCheckDeliver( - t *testing.T, txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, - chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, -) (sdk.GasInfo, *sdk.Result, error) { - tx, err := helpers.GenSignedMockTx( - rand.New(rand.NewSource(time.Now().UnixNano())), - txCfg, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, - chainID, - accNums, - accSeqs, - priv..., - ) - require.NoError(t, err) - txBytes, err := txCfg.TxEncoder()(tx) - require.Nil(t, err) - - // Must simulate now as CheckTx doesn't run Msgs anymore - _, res, err := app.Simulate(txBytes) - - if expSimPass { - require.NoError(t, err) - require.NotNil(t, res) - } else { - require.Error(t, err) - require.Nil(t, res) - } - - // Simulate a sending a transaction and committing a block - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) - - if expPass { - require.NoError(t, err) - require.NotNil(t, res) - } else { - require.Error(t, err) - require.Nil(t, res) - } - - app.EndBlock(abci.RequestEndBlock{}) - app.Commit() - - return gInfo, res, err -} - // GenSequenceOfTxs generates a set of signed transactions of messages, such // that they differ only by having the sequence numbers incremented between // every transaction. diff --git a/simapp/test_simapp.go b/simapp/test_simapp.go deleted file mode 100644 index 3d0853531..000000000 --- a/simapp/test_simapp.go +++ /dev/null @@ -1,346 +0,0 @@ -package simapp - -import ( - "encoding/json" - "math/rand" - "reflect" - "time" - - abci "github.com/tendermint/tendermint/abci/types" - tmjson "github.com/tendermint/tendermint/libs/json" - tmproto "github.com/tendermint/tendermint/proto/tendermint/types" - tmtypes "github.com/tendermint/tendermint/types" - - bam "github.com/cosmos/cosmos-sdk/baseapp" - "github.com/cosmos/cosmos-sdk/client" - codectypes "github.com/cosmos/cosmos-sdk/codec/types" - cryptocodec "github.com/cosmos/cosmos-sdk/crypto/codec" - "github.com/cosmos/cosmos-sdk/crypto/keys/secp256k1" - cryptotypes "github.com/cosmos/cosmos-sdk/crypto/types" - "github.com/cosmos/cosmos-sdk/simapp/helpers" - "github.com/cosmos/cosmos-sdk/testutil/mock" - sdk "github.com/cosmos/cosmos-sdk/types" - authtypes "github.com/cosmos/cosmos-sdk/x/auth/types" - banktypes "github.com/cosmos/cosmos-sdk/x/bank/types" - stakingtypes "github.com/cosmos/cosmos-sdk/x/staking/types" - - // cheqd specific imports - cheqdapp "github.com/cheqd/cheqd-node/app" - didtypes "github.com/cheqd/cheqd-node/x/did/types" - resourcetypes "github.com/cheqd/cheqd-node/x/resource/types" -) - -// NewSimappWithCustomOptions initializes a new SimApp with custom options. -func NewSimappWithCustomOptionsForGinkgo(isCheckTx bool, options SetupOptions) *SimApp { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - // generate genesis account - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), - } - - app := NewSimApp(options.Logger, options.DB, nil, true, options.SkipUpgradeHeights, options.HomePath, options.InvCheckPeriod, options.EncConfig, options.AppOpts) - genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) - genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balance) - - if !isCheckTx { - // init chain must be called to stop deliverState from being nil - stateBytes, err := tmjson.MarshalIndent(genesisState, "", " ") - if err != nil { - panic(err) - } - - // Initialize the chain - app.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - } - - return app -} - -// Setup initializes a new SimApp. A Nop logger is set in SimApp. -func SetupForGinkgo(isCheckTx bool) *SimApp { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - // generate genesis account - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), - } - - app := SetupWithGenesisValSetForGinkgo(valSet, []authtypes.GenesisAccount{acc}, balance) - - return app -} - -// Setup initializes a new SimApp. A Nop logger is set in SimApp. -func SetupTest(isCheckTx bool) *SimApp { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - // generate genesis account - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balance := banktypes.Balance{ - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(didtypes.BaseMinimalDenom, sdk.NewInt(100000000000000))), - } - - app := SetupWithGenesisValSetForGinkgo(valSet, []authtypes.GenesisAccount{acc}, balance) - - return app -} - -func genesisStateWithValSetForGinkgo( - app *SimApp, genesisState cheqdapp.GenesisState, - valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, - balances ...banktypes.Balance, -) cheqdapp.GenesisState { - // set genesis accounts - authGenesis := authtypes.NewGenesisState(authtypes.DefaultParams(), genAccs) - genesisState[authtypes.ModuleName] = app.AppCodec().MustMarshalJSON(authGenesis) - - validators := make([]stakingtypes.Validator, 0, len(valSet.Validators)) - delegations := make([]stakingtypes.Delegation, 0, len(valSet.Validators)) - - bondAmt := sdk.DefaultPowerReduction - - for _, val := range valSet.Validators { - pk, err := cryptocodec.FromTmPubKeyInterface(val.PubKey) - 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: bondAmt, - 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(), - } - validators = append(validators, validator) - delegations = append(delegations, stakingtypes.NewDelegation(genAccs[0].GetAddress(), val.Address.Bytes(), sdk.OneDec())) - - } - // set validators and delegations - stakingGenesis := stakingtypes.NewGenesisState(stakingtypes.DefaultParams(), validators, delegations) - genesisState[stakingtypes.ModuleName] = app.AppCodec().MustMarshalJSON(stakingGenesis) - - totalSupply := sdk.NewCoins() - for _, b := range balances { - // add genesis acc tokens to total supply - totalSupply = totalSupply.Add(b.Coins...) - } - - for range delegations { - // add delegated tokens to total supply - totalSupply = totalSupply.Add(sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)) - } - - // add bonded amount to bonded pool module account - balances = append(balances, banktypes.Balance{ - Address: authtypes.NewModuleAddress(stakingtypes.BondedPoolName).String(), - Coins: sdk.Coins{sdk.NewCoin(sdk.DefaultBondDenom, bondAmt)}, - }) - - // update total supply - bankGenesis := banktypes.NewGenesisState(banktypes.DefaultGenesisState().Params, balances, totalSupply, []banktypes.Metadata{}) - genesisState[banktypes.ModuleName] = app.AppCodec().MustMarshalJSON(bankGenesis) - - // set did module genesis state - didGenesis := didtypes.DefaultGenesis() - genesisState[didtypes.ModuleName] = app.AppCodec().MustMarshalJSON(didGenesis) - - // set resource module genesis state - resourceGenesis := resourcetypes.DefaultGenesis() - genesisState[resourcetypes.ModuleName] = app.AppCodec().MustMarshalJSON(resourceGenesis) - - return genesisState -} - -// SetupWithGenesisValSet initializes a new SimApp 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 simapp from first genesis -// account. A Nop logger is set in SimApp. -func SetupWithGenesisValSetForGinkgo(valSet *tmtypes.ValidatorSet, genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { - app, genesisState := setup(true, 5) - genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, genAccs, balances...) - - stateBytes, err := json.MarshalIndent(genesisState, "", " ") - if err != nil { - panic(err) - } - - // init chain will set the validator set and initialize the genesis accounts - app.InitChain( - abci.RequestInitChain{ - Validators: []abci.ValidatorUpdate{}, - ConsensusParams: DefaultConsensusParams, - AppStateBytes: stateBytes, - }, - ) - - // commit genesis changes - app.Commit() - app.BeginBlock(abci.RequestBeginBlock{Header: tmproto.Header{ - Height: app.LastBlockHeight() + 1, - AppHash: app.LastCommitID().Hash, - ValidatorsHash: valSet.Hash(), - NextValidatorsHash: valSet.Hash(), - }}) - - return app -} - -// SetupWithGenesisAccounts initializes a new SimApp with the provided genesis -// accounts and possible balances. -func SetupWithGenesisAccountsForGinkgo(genAccs []authtypes.GenesisAccount, balances ...banktypes.Balance) *SimApp { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - return SetupWithGenesisValSetForGinkgo(valSet, genAccs, balances...) -} - -// GenesisStateWithSingleValidator initializes GenesisState with a single validator and genesis accounts -// that also act as delegators. -func GenesisStateWithSingleValidatorForGinkgo(app *SimApp) cheqdapp.GenesisState { - privVal := mock.NewPV() - pubKey, err := privVal.GetPubKey() - if err != nil { - panic(err) - } - - // create validator set with single validator - validator := tmtypes.NewValidator(pubKey, 1) - valSet := tmtypes.NewValidatorSet([]*tmtypes.Validator{validator}) - - // generate genesis account - senderPrivKey := secp256k1.GenPrivKey() - acc := authtypes.NewBaseAccount(senderPrivKey.PubKey().Address().Bytes(), senderPrivKey.PubKey(), 0, 0) - balances := []banktypes.Balance{ - { - Address: acc.GetAddress().String(), - Coins: sdk.NewCoins(sdk.NewCoin(sdk.DefaultBondDenom, sdk.NewInt(100000000000000))), - }, - } - - genesisState := cheqdapp.NewDefaultGenesisState(app.appCodec) - genesisState = genesisStateWithValSetForGinkgo(app, genesisState, valSet, []authtypes.GenesisAccount{acc}, balances...) - - return genesisState -} - -// CheckBalance checks the balance of an account. -func CheckBalanceForGinkgo(app *SimApp, addr sdk.AccAddress, balances sdk.Coins) { - ctxCheck := app.BaseApp.NewContext(true, tmproto.Header{}) - if reflect.DeepEqual(balances, app.BankKeeper.GetAllBalances(ctxCheck, addr)) { - panic("Invalid balance of account") - } -} - -// SignCheckDeliver checks a generated signed transaction and simulates a -// block commitment with the given transaction. A test assertion is made using -// the parameter 'expPass' against the result. A corresponding result is -// returned. -func SignCheckDeliverForGinkgo( - txCfg client.TxConfig, app *bam.BaseApp, header tmproto.Header, msgs []sdk.Msg, - chainID string, accNums, accSeqs []uint64, expSimPass, expPass bool, priv ...cryptotypes.PrivKey, -) (sdk.GasInfo, *sdk.Result, error) { - tx, err := helpers.GenSignedMockTx( - rand.New(rand.NewSource(time.Now().UnixNano())), - txCfg, - msgs, - sdk.Coins{sdk.NewInt64Coin(sdk.DefaultBondDenom, 0)}, - helpers.DefaultGenTxGas, - chainID, - accNums, - accSeqs, - priv..., - ) - if err != nil { - panic(err) - } - txBytes, err := txCfg.TxEncoder()(tx) - if err != nil { - panic(err) - } - - // Must simulate now as CheckTx doesn't run Msgs anymore - _, res, err := app.Simulate(txBytes) - - if expSimPass { - if err != nil || res == nil { - panic(err) - } - } else { - if err == nil || res != nil { - panic(err) - } - } - - // Simulate a sending a transaction and committing a block - app.BeginBlock(abci.RequestBeginBlock{Header: header}) - gInfo, res, err := app.SimDeliver(txCfg.TxEncoder(), tx) - - if expPass { - if err != nil || res == nil { - panic(err) - } - } else { - if err == nil || res != nil { - panic(err) - } - } - - app.EndBlock(abci.RequestEndBlock{}) - app.Commit() - - return gInfo, res, err -} diff --git a/x/did/keeper/keeper_param_change_proposal_test.go b/x/did/keeper/keeper_param_change_proposal_test.go index 40de8c767..daf1fade1 100644 --- a/x/did/keeper/keeper_param_change_proposal_test.go +++ b/x/did/keeper/keeper_param_change_proposal_test.go @@ -1,8 +1,6 @@ package keeper_test import ( - "testing" - "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -13,6 +11,9 @@ import ( govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" ) type HandlerTestSuite struct { @@ -23,36 +24,49 @@ type HandlerTestSuite struct { govHandler govv1beta1.Handler } -func (suite *HandlerTestSuite) SetupTest() { - suite.app = cheqdsimapp.Setup(suite.T(), false) +func (suite *HandlerTestSuite) SetupTest() error { + var err error + suite.app, err = cheqdsimapp.Setup(false) + if err != nil { + return err + } suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) suite.govHandler = params.NewParamChangeProposalHandler(suite.app.ParamsKeeper) -} - -func TestHandlerTestSuite(t *testing.T) { - suite.Run(t, new(HandlerTestSuite)) + return nil } func testProposal(changes ...proposal.ParamChange) *proposal.ParameterChangeProposal { return proposal.NewParameterChangeProposal("title", "description", changes) } -func (suite *HandlerTestSuite) TestProposalHandler() { - testCases := []struct { - name string - proposal *proposal.ParameterChangeProposal - onHandle func() - expErr bool - errMsg string - }{ - { - "all fields", +type TestCaseKeeperProposal struct { + proposal *proposal.ParameterChangeProposal + onHandle func(*HandlerTestSuite) + expErr bool + errMsg string +} + +var _ = DescribeTable("Proposal Handler", func(testCase TestCaseKeeperProposal) { + handlerSuite := new(HandlerTestSuite) + err := handlerSuite.SetupTest() + Expect(err).To(BeNil()) + + err = handlerSuite.govHandler(handlerSuite.ctx, testCase.proposal) + if testCase.expErr { + Expect(err).NotTo(BeNil()) + } else { + Expect(err).To(BeNil()) + testCase.onHandle(handlerSuite) + } +}, + Entry("all fields", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "10000000000"}, "update_did": {"denom": "ncheq", "amount": "4000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() { + func(handlerSuite *HandlerTestSuite) { expectedFeeParams := didtypes.FeeParams{ TxTypes: map[string]sdk.Coin{ didtypes.DefaultKeyCreateDid: {Denom: didtypes.BaseMinimalDenom, Amount: sdk.NewInt(10000000000)}, @@ -62,21 +76,21 @@ func (suite *HandlerTestSuite) TestProposalHandler() { BurnFactor: sdk.MustNewDecFromStr("0.600000000000000000"), } - feeParams := suite.app.DidKeeper.GetParams(suite.ctx) + feeParams := handlerSuite.app.DidKeeper.GetParams(handlerSuite.ctx) - suite.Require().Equal(expectedFeeParams, feeParams) + Expect(expectedFeeParams).To(Equal(feeParams)) }, false, "", - }, - { - "new msg type added", + }), + Entry("new msg type added", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "5000000000"}, "update_did": {"denom": "ncheq", "amount": "2000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "1000000000"}, "new_msg_type": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.500000000000000000"}`, }), - func() { + func(handlerSuite *HandlerTestSuite) { expectedFeeParams := didtypes.FeeParams{ TxTypes: map[string]sdk.Coin{ didtypes.DefaultKeyCreateDid: {Denom: didtypes.BaseMinimalDenom, Amount: sdk.NewInt(didtypes.DefaultCreateDidTxFee)}, @@ -87,109 +101,101 @@ func (suite *HandlerTestSuite) TestProposalHandler() { BurnFactor: sdk.MustNewDecFromStr(didtypes.DefaultBurnFactor), } - feeParams := suite.app.DidKeeper.GetParams(suite.ctx) + feeParams := handlerSuite.app.DidKeeper.GetParams(handlerSuite.ctx) - suite.Require().Equal(expectedFeeParams, feeParams) + Expect(expectedFeeParams).To(Equal(feeParams)) }, false, "", - }, - { - "empty value", + }), + Entry("empty value", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - { - "omit fields", + ), + Entry("omit fields", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: ` - { - "tx_types": { - "create_did": {"denom": "ncheq", "amount": "10000000000"}, - "update_did": {"denom": "ncheq", "amount": "4000000000"} - }, - "burn_factor": "0.600000000000000000" - }`, + { + "tx_types": { + "create_did": {"denom": "ncheq", "amount": "10000000000"}, + "update_did": {"denom": "ncheq", "amount": "4000000000"} + }, + "burn_factor": "0.600000000000000000" + }`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - { - "invalid value: case `create_did` amount 0", + ), + Entry("invalid value: case `create_did` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "0"}, "update_did": {"denom": "ncheq", "amount": "4000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - { - "invalid value: case `update_did` amount 0", + ), + Entry("invalid value: case `update_did` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "10000000000"}, "update_did": {"denom": "ncheq", "amount": "0"}, "deactivate_did": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `deactivate_did` amount 0", + }), + Entry("invalid value: case `deactivate_did` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "10000000000"}, "update_did": {"denom": "ncheq", "amount": "4000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "0"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - { - "invalid value: case `burn_factor` -1", + ), + Entry("invalid value: case `burn_factor` -1", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "10000000000"}, "update_did": {"denom": "ncheq", "amount": "4000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "-1"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - { - "invalid value: case `burn_factor` 1.1", + ), + Entry("invalid value: case `burn_factor` 1.1", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: didtypes.ModuleName, Key: string(didtypes.ParamStoreKeyFeeParams), Value: `{"tx_types": {"create_did": {"denom": "ncheq", "amount": "10000000000"}, "update_did": {"denom": "ncheq", "amount": "4000000000"}, "deactivate_did": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "1.1"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - err := suite.govHandler(suite.ctx, tc.proposal) - if tc.expErr { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - tc.onHandle() - } - }) - } -} + ), +) diff --git a/x/did/keeper/keeper_suite_test.go b/x/did/keeper/keeper_suite_test.go new file mode 100644 index 000000000..3a9fc7d85 --- /dev/null +++ b/x/did/keeper/keeper_suite_test.go @@ -0,0 +1,13 @@ +package keeper_test + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestKeeper(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Keeper Suite") +} diff --git a/x/resource/keeper/keeper_param_change_proposal_test.go b/x/resource/keeper/keeper_param_change_proposal_test.go index 707902af0..73ff29707 100644 --- a/x/resource/keeper/keeper_param_change_proposal_test.go +++ b/x/resource/keeper/keeper_param_change_proposal_test.go @@ -1,8 +1,6 @@ package keeper_test import ( - "testing" - "github.com/stretchr/testify/suite" tmproto "github.com/tendermint/tendermint/proto/tendermint/types" @@ -13,6 +11,9 @@ import ( govv1beta1 "github.com/cosmos/cosmos-sdk/x/gov/types/v1beta1" "github.com/cosmos/cosmos-sdk/x/params" "github.com/cosmos/cosmos-sdk/x/params/types/proposal" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" ) type HandlerTestSuite struct { @@ -23,36 +24,53 @@ type HandlerTestSuite struct { govHandler govv1beta1.Handler } -func (suite *HandlerTestSuite) SetupTest() { - suite.app = cheqdsimapp.Setup(suite.T(), false) +func (suite *HandlerTestSuite) SetupTest() error { + var err error + suite.app, err = cheqdsimapp.Setup(false) + if err != nil { + return err + } suite.ctx = suite.app.BaseApp.NewContext(false, tmproto.Header{}) suite.govHandler = params.NewParamChangeProposalHandler(suite.app.ParamsKeeper) + return nil } -func TestHandlerTestSuite(t *testing.T) { - suite.Run(t, new(HandlerTestSuite)) -} +// func TestHandlerTestSuite(t *testing.T) { +// suite.Run(t, new(HandlerTestSuite)) +// } func testProposal(changes ...proposal.ParamChange) *proposal.ParameterChangeProposal { return proposal.NewParameterChangeProposal("title", "description", changes) } -func (suite *HandlerTestSuite) TestProposalHandler() { - testCases := []struct { - name string - proposal *proposal.ParameterChangeProposal - onHandle func() - expErr bool - errMsg string - }{ - { - "all fields", +type TestCaseKeeperProposal struct { + proposal *proposal.ParameterChangeProposal + onHandle func(*HandlerTestSuite) + expErr bool + errMsg string +} + +var _ = DescribeTable("Proposal Handler", func(testcase TestCaseKeeperProposal) { + handlerSuite := new(HandlerTestSuite) + err := handlerSuite.SetupTest() + Expect(err).To(BeNil()) + + err = handlerSuite.govHandler(handlerSuite.ctx, testcase.proposal) + if testcase.expErr { + Expect(err).NotTo(BeNil()) + } else { + Expect(err).To(BeNil()) + testcase.onHandle(handlerSuite) + } +}, + Entry("all fields", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "10000000000"}, "json": {"denom": "ncheq", "amount": "4000000000"}, "default": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() { + func(handlerSuite *HandlerTestSuite) { expectedFeeParams := resourcetypes.FeeParams{ MediaTypes: map[string]sdk.Coin{ resourcetypes.DefaultKeyCreateResourceImage: {Denom: resourcetypes.BaseMinimalDenom, Amount: sdk.NewInt(10000000000)}, @@ -62,21 +80,21 @@ func (suite *HandlerTestSuite) TestProposalHandler() { BurnFactor: sdk.MustNewDecFromStr("0.600000000000000000"), } - feeParams := suite.app.ResourceKeeper.GetParams(suite.ctx) + feeParams := handlerSuite.app.ResourceKeeper.GetParams(handlerSuite.ctx) - suite.Require().Equal(expectedFeeParams, feeParams) + Expect(expectedFeeParams).To(Equal(feeParams)) }, false, "", - }, - { - "new media type added", + }), + Entry("new media type added", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "5000000000"}, "json": {"denom": "ncheq", "amount": "2000000000"}, "default": {"denom": "ncheq", "amount": "1000000000"}, "text/html": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.500000000000000000"}`, }), - func() { + func(handlerSuite *HandlerTestSuite) { expectedFeeParams := resourcetypes.FeeParams{ MediaTypes: map[string]sdk.Coin{ resourcetypes.DefaultKeyCreateResourceImage: {Denom: resourcetypes.BaseMinimalDenom, Amount: sdk.NewInt(resourcetypes.DefaultCreateResourceImageFee)}, @@ -87,26 +105,26 @@ func (suite *HandlerTestSuite) TestProposalHandler() { BurnFactor: sdk.MustNewDecFromStr(resourcetypes.DefaultBurnFactor), } - feeParams := suite.app.ResourceKeeper.GetParams(suite.ctx) + feeParams := handlerSuite.app.ResourceKeeper.GetParams(handlerSuite.ctx) - suite.Require().Equal(expectedFeeParams, feeParams) + Expect(expectedFeeParams).To(Equal(feeParams)) }, false, "", - }, - { - "empty value", + }), + Entry("empty value", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "omit fields", + }), + Entry("omit fields", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), @@ -119,77 +137,63 @@ func (suite *HandlerTestSuite) TestProposalHandler() { "burn_factor": "0.600000000000000000" }`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `image` amount 0", + }), + Entry("invalid value: case `image` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "0"}, "json": {"denom": "ncheq", "amount": "4000000000"}, "default": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `json` amount 0", + }), + Entry("invalid value: case `json` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "10000000000"}, "json": {"denom": "ncheq", "amount": "0"}, "default": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `default` amount 0", + }), + Entry("invalid value: case `default` amount 0", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "10000000000"}, "json": {"denom": "ncheq", "amount": "4000000000"}, "default": {"denom": "ncheq", "amount": "0"}}, "burn_factor": "0.600000000000000000"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `burn_factor` -1", + }), + Entry("invalid value: case `burn_factor` -1", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "10000000000"}, "json": {"denom": "ncheq", "amount": "4000000000"}, "default": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "-1"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - { - "invalid value: case `burn_factor` 1.1", + }), + Entry("invalid value: case `burn_factor` 1.1", + TestCaseKeeperProposal{ testProposal(proposal.ParamChange{ Subspace: resourcetypes.ModuleName, Key: string(resourcetypes.ParamStoreKeyFeeParams), Value: `{"media_types": {"image": {"denom": "ncheq", "amount": "10000000000"}, "json": {"denom": "ncheq", "amount": "4000000000"}, "default": {"denom": "ncheq", "amount": "2000000000"}}, "burn_factor": "1.1"}`, }), - func() {}, + func(*HandlerTestSuite) {}, true, "", - }, - } - - for _, tc := range testCases { - tc := tc - suite.Run(tc.name, func() { - err := suite.govHandler(suite.ctx, tc.proposal) - if tc.expErr { - suite.Require().Error(err) - } else { - suite.Require().NoError(err) - tc.onHandle() - } - }) - } -} + }), +) diff --git a/x/resource/keeper/keeper_suite_test.go b/x/resource/keeper/keeper_suite_test.go new file mode 100644 index 000000000..3a9fc7d85 --- /dev/null +++ b/x/resource/keeper/keeper_suite_test.go @@ -0,0 +1,13 @@ +package keeper_test + +import ( + "testing" + + . "github.com/onsi/ginkgo/v2" + . "github.com/onsi/gomega" +) + +func TestKeeper(t *testing.T) { + RegisterFailHandler(Fail) + RunSpecs(t, "Keeper Suite") +}