Skip to content

Commit

Permalink
Add ctx app test helper (#406)
Browse files Browse the repository at this point in the history
Co-authored-by: DongLieu <duongduydongtq@gmail.com>
  • Loading branch information
hieuvubk and DongLieu authored Dec 1, 2022
1 parent df2fcea commit 0e0238b
Show file tree
Hide file tree
Showing 37 changed files with 556 additions and 570 deletions.
44 changes: 15 additions & 29 deletions app/apptesting/test_helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,51 +48,35 @@ type AppTestHelper struct {
QueryHelper *baseapp.QueryServiceTestHelper
TestAccs []sdk.AccAddress
IcaAddresses map[string]string
Ctx sdk.Context
}

// AppTestHelper Constructor
func (s *AppTestHelper) Setup() {
s.App = app.InitStrideTestApp(true)
s.Ctx = s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: StrideChainID})
s.QueryHelper = &baseapp.QueryServiceTestHelper{
GRPCQueryRouter: s.App.GRPCQueryRouter(),
Ctx: s.Ctx(),
Ctx: s.Ctx,
}
s.TestAccs = CreateRandomAccounts(3)
s.IbcEnabled = false
s.IcaAddresses = make(map[string]string)
}

// Dynamically gets the context of the Stride Chain
func (s *AppTestHelper) Ctx() sdk.Context {
// If IBC support is enabled, return a dynamic context that updates with each block
if s.IbcEnabled {
return s.StrideChain.GetContext()
}
// Otherwise return a mock context
return s.App.BaseApp.NewContext(false, tmtypes.Header{Height: 1, ChainID: StrideChainID})
}

// Dynamically gets the context of the Host Chain
func (s *AppTestHelper) HostCtx() sdk.Context {
// Host context can only be used if IBC support has been enabled
s.Require().NotNil(s.HostChain, "HostChain must be initialzed before accessing a context. "+
"To initailze run `s.SetupIBCChains(chainID)`, `s.CreateTransferChannel(chainID)` or `s.CreateICAChannel(owner)`")

return s.HostChain.GetContext()
}

// Mints coins directly to a module account
func (s *AppTestHelper) FundModuleAccount(moduleName string, amount sdk.Coin) {
err := s.App.BankKeeper.MintCoins(s.Ctx(), moduleName, sdk.NewCoins(amount))
err := s.App.BankKeeper.MintCoins(s.Ctx, moduleName, sdk.NewCoins(amount))
s.Require().NoError(err)
}

// Mints and sends coins to a user account
func (s *AppTestHelper) FundAccount(acc sdk.AccAddress, amount sdk.Coin) {
amountCoins := sdk.NewCoins(amount)
err := s.App.BankKeeper.MintCoins(s.Ctx(), minttypes.ModuleName, amountCoins)
err := s.App.BankKeeper.MintCoins(s.Ctx, minttypes.ModuleName, amountCoins)
s.Require().NoError(err)
err = s.App.BankKeeper.SendCoinsFromModuleToAccount(s.Ctx(), minttypes.ModuleName, acc, amountCoins)
err = s.App.BankKeeper.SendCoinsFromModuleToAccount(s.Ctx, minttypes.ModuleName, acc, amountCoins)
s.Require().NoError(err)
}

Expand Down Expand Up @@ -148,7 +132,7 @@ func (s *AppTestHelper) CreateTransferChannel(hostChainID string) {
// Replace stride and host apps with those from TestingApp
s.App = s.StrideChain.App.(*app.StrideApp)
s.HostApp = s.HostChain.GetSimApp()

s.Ctx = s.StrideChain.GetContext()
// Finally confirm the channel was setup properly
s.Require().Equal(ibctesting.FirstClientID, s.TransferPath.EndpointA.ClientID, "stride clientID")
s.Require().Equal(ibctesting.FirstConnectionID, s.TransferPath.EndpointA.ConnectionID, "stride connectionID")
Expand All @@ -163,7 +147,7 @@ func (s *AppTestHelper) CreateTransferChannel(hostChainID string) {
// Also creates a transfer channel is if hasn't been done yet
func (s *AppTestHelper) CreateICAChannel(owner string) string {
// If we have yet to create a client/connection (through creating a transfer channel), do that here
_, transferChannelExists := s.App.IBCKeeper.ChannelKeeper.GetChannel(s.Ctx(), ibctesting.TransferPort, ibctesting.FirstChannelID)
_, transferChannelExists := s.App.IBCKeeper.ChannelKeeper.GetChannel(s.Ctx, ibctesting.TransferPort, ibctesting.FirstChannelID)
if !transferChannelExists {
ownerSplit := strings.Split(owner, ".")
s.Require().Equal(2, len(ownerSplit), "owner should be of the form: {HostZone}.{AccountName}")
Expand All @@ -177,6 +161,7 @@ func (s *AppTestHelper) CreateICAChannel(owner string) string {
icaPath = CopyConnectionAndClientToPath(icaPath, s.TransferPath)

// Register the ICA and complete the handshake

s.RegisterInterchainAccount(icaPath.EndpointA, owner)

err := icaPath.EndpointB.ChanOpenTry()
Expand All @@ -188,19 +173,20 @@ func (s *AppTestHelper) CreateICAChannel(owner string) string {
err = icaPath.EndpointB.ChanOpenConfirm()
s.Require().NoError(err, "ChanOpenConfirm error")

s.Ctx = s.StrideChain.GetContext()
// Confirm the ICA channel was created properly
portID := icaPath.EndpointA.ChannelConfig.PortID
channelID := icaPath.EndpointA.ChannelID
_, found := s.App.IBCKeeper.ChannelKeeper.GetChannel(s.Ctx(), portID, channelID)
_, found := s.App.IBCKeeper.ChannelKeeper.GetChannel(s.Ctx, portID, channelID)
s.Require().True(found, "Channel not found after creation, PortID: %s, ChannelID: %s", portID, channelID)

// Store the account address
icaAddress, found := s.App.ICAControllerKeeper.GetInterchainAccountAddress(s.Ctx(), ibctesting.FirstConnectionID, portID)
icaAddress, found := s.App.ICAControllerKeeper.GetInterchainAccountAddress(s.Ctx, ibctesting.FirstConnectionID, portID)
s.Require().True(found, "can't get ICA address")
s.IcaAddresses[owner] = icaAddress

// Finally set the active channel
s.App.ICAControllerKeeper.SetActiveChannelID(s.Ctx(), ibctesting.FirstConnectionID, portID, channelID)
s.App.ICAControllerKeeper.SetActiveChannelID(s.Ctx, ibctesting.FirstConnectionID, portID, channelID)

return channelID
}
Expand All @@ -213,9 +199,9 @@ func (s *AppTestHelper) RegisterInterchainAccount(endpoint *ibctesting.Endpoint,
s.Require().NoError(err, "owner to portID error")

// Get the next channel available and register the ICA
channelSequence := s.App.IBCKeeper.ChannelKeeper.GetNextChannelSequence(s.Ctx())
channelSequence := s.App.IBCKeeper.ChannelKeeper.GetNextChannelSequence(s.Ctx)

err = s.App.ICAControllerKeeper.RegisterInterchainAccount(s.Ctx(), endpoint.ConnectionID, owner)
err = s.App.ICAControllerKeeper.RegisterInterchainAccount(s.Ctx, endpoint.ConnectionID, owner)
s.Require().NoError(err, "register interchain account error")

// Commit the state
Expand Down
14 changes: 7 additions & 7 deletions x/epochs/keeper/abci_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 1,
expInitialEpochStartTime: now,
fn: func() {
ctx := suite.Ctx().WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
ctx := suite.Ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.App.EpochsKeeper.BeginBlocker(ctx)
epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(ctx, "monthly")
},
Expand All @@ -38,7 +38,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 1,
expInitialEpochStartTime: now,
fn: func() {
ctx := suite.Ctx().WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
ctx := suite.Ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.App.EpochsKeeper.BeginBlocker(ctx)
ctx = ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 31))
suite.App.EpochsKeeper.BeginBlocker(ctx)
Expand All @@ -52,7 +52,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
ctx := suite.Ctx().WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
ctx := suite.Ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.App.EpochsKeeper.BeginBlocker(ctx)
ctx = ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.App.EpochsKeeper.BeginBlocker(ctx)
Expand All @@ -65,7 +65,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
ctx := suite.Ctx().WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
ctx := suite.Ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.App.EpochsKeeper.BeginBlocker(ctx)
ctx = ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.App.EpochsKeeper.BeginBlocker(ctx)
Expand All @@ -80,7 +80,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
expCurrentEpoch: 2,
expInitialEpochStartTime: now,
fn: func() {
ctx := suite.Ctx().WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
ctx := suite.Ctx.WithBlockHeight(2).WithBlockTime(now.Add(time.Second))
suite.App.EpochsKeeper.BeginBlocker(ctx)
ctx = ctx.WithBlockHeight(3).WithBlockTime(now.Add(time.Hour * 24 * 32))
suite.App.EpochsKeeper.BeginBlocker(ctx)
Expand All @@ -94,7 +94,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
for i, tc := range testCases {
suite.Run(fmt.Sprintf("Case %d", i), func() {
suite.SetupTest() // reset
ctx := suite.Ctx()
ctx := suite.Ctx

// On init genesis, default epochs information is set
// To check init genesis again, should make it fresh status
Expand Down Expand Up @@ -133,7 +133,7 @@ func (suite *KeeperTestSuite) TestEpochInfoChangesBeginBlockerAndInitGenesis() {
}

func (suite *KeeperTestSuite) TestEpochStartingOneMonthAfterInitGenesis() {
ctx := suite.Ctx()
ctx := suite.Ctx
// On init genesis, default epochs information is set
// To check init genesis again, should make it fresh status
epochInfos := suite.App.EpochsKeeper.AllEpochInfos(ctx)
Expand Down
2 changes: 1 addition & 1 deletion x/epochs/keeper/epoch_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import (

func (suite *KeeperTestSuite) TestEpochLifeCycle() {
suite.SetupTest()
ctx := suite.Ctx()
ctx := suite.Ctx

epochInfo := types.EpochInfo{
Identifier: "monthly",
Expand Down
2 changes: 1 addition & 1 deletion x/epochs/keeper/grpc_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ func (suite *KeeperTestSuite) TestQueryEpochInfos() {
suite.SetupTest()
queryClient := suite.queryClient

chainStartTime := suite.Ctx().BlockTime()
chainStartTime := suite.Ctx.BlockTime()

// Invalid param
epochInfosResponse, err := queryClient.EpochInfos(gocontext.Background(), &types.QueryEpochsInfoRequest{})
Expand Down
28 changes: 14 additions & 14 deletions x/interchainquery/keeper/msg_submit_query_response_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ func (s *KeeperTestSuite) SetupMsgSubmitQueryResponse() MsgSubmitQueryResponseTe
s.CreateTransferChannel(HostChainId)

// define the query
goCtx := sdk.WrapSDKContext(s.Ctx())
h, err := s.App.StakeibcKeeper.GetLightClientHeightSafely(s.Ctx(), s.TransferPath.EndpointA.ConnectionID)
goCtx := sdk.WrapSDKContext(s.Ctx)
h, err := s.App.StakeibcKeeper.GetLightClientHeightSafely(s.Ctx, s.TransferPath.EndpointA.ConnectionID)
s.Require().NoError(err)
height := int64(h - 1) // start at the (LC height) - 1 height, which is the height the query executes at!
result := []byte("result-example")
Expand Down Expand Up @@ -66,7 +66,7 @@ func (s *KeeperTestSuite) SetupMsgSubmitQueryResponse() MsgSubmitQueryResponseTe
func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_WrongProof() {
tc := s.SetupMsgSubmitQueryResponse()

s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)

resp, err := s.GetMsgServer().SubmitQueryResponse(tc.goCtx, &tc.validMsg)
s.Require().ErrorContains(err, "unable to verify membership proof: proof cannot be empty")
Expand All @@ -77,24 +77,24 @@ func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_UnknownId() {
tc := s.SetupMsgSubmitQueryResponse()

tc.query.Id = tc.query.Id + "INVALID_SUFFIX" // create an invalid query id
s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)

resp, err := s.GetMsgServer().SubmitQueryResponse(tc.goCtx, &tc.validMsg)
s.Require().NoError(err)
s.Require().NotNil(resp)
s.Require().Equal(&types.MsgSubmitQueryResponseResponse{}, resp)

// check that the query is STILL in the store, as it should NOT be deleted because the query was not found
_, found := s.App.InterchainqueryKeeper.GetQuery(s.Ctx(), tc.query.Id)
_, found := s.App.InterchainqueryKeeper.GetQuery(s.Ctx, tc.query.Id)
s.Require().True(found)
}

func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_ExceededTtl() {
tc := s.SetupMsgSubmitQueryResponse()

tc.query.Ttl = uint64(1) // set ttl to be expired
s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
exceeded, err := s.App.InterchainqueryKeeper.HasQueryExceededTtl(s.Ctx(), &tc.validMsg, tc.query)
s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)
exceeded, err := s.App.InterchainqueryKeeper.HasQueryExceededTtl(s.Ctx, &tc.validMsg, tc.query)
s.Require().NoError(err)
s.Require().True(exceeded)
}
Expand All @@ -103,24 +103,24 @@ func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_NotExceededTtl() {
tc := s.SetupMsgSubmitQueryResponse()

tc.query.Ttl = uint64(2545450064) * uint64(1000000000) // for test clarity, re-set ttl to August 2050, mult by nano conversion factor
s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
exceeded, err := s.App.InterchainqueryKeeper.HasQueryExceededTtl(s.Ctx(), &tc.validMsg, tc.query)
s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)
exceeded, err := s.App.InterchainqueryKeeper.HasQueryExceededTtl(s.Ctx, &tc.validMsg, tc.query)
s.Require().NoError(err)
s.Require().False(exceeded)

// check that the query is not in the store anymore, as it should be deleted
_, found := s.App.InterchainqueryKeeper.GetQuery(s.Ctx(), tc.query.Id)
_, found := s.App.InterchainqueryKeeper.GetQuery(s.Ctx, tc.query.Id)
s.Require().True(found)
}

func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_FindAndInvokeCallback_WrongHostZone() {
tc := s.SetupMsgSubmitQueryResponse()

s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)

// rather than testing by executing the callback in its entirety,
// check by invoking it without a registered host zone and catching the appropriate error
err := s.App.InterchainqueryKeeper.InvokeCallback(s.Ctx(), &tc.validMsg, tc.query)
err := s.App.InterchainqueryKeeper.InvokeCallback(s.Ctx, &tc.validMsg, tc.query)
s.Require().ErrorContains(err, "no registered zone for queried chain ID", "callback was invoked")
}

Expand All @@ -129,7 +129,7 @@ func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_FindAndInvokeCallback_Wrong
// // ...down the line, we may want to write tests here that verify the merkle check using proofs from tendermint's proof_test library, https://github.com/tendermint/tendermint/blob/75d51e18f740c7cbfb7d8b4d49182ee6c7f41982/crypto/merkle/proof_test.go
// func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_VerifyProofSuccess() {
// tc := s.SetupMsgSubmitQueryResponse()
// s.App.InterchainqueryKeeper.SetQuery(s.Ctx(), tc.query)
// s.App.InterchainqueryKeeper.SetQuery(s.Ctx, tc.query)

// // set the msgHeight to the light client's height (required to verify retured proofs)
// clientHeight := s.HostChain.GetClientState(s.TransferPath.EndpointA.ClientID).GetLatestHeight().GetRevisionHeight()
Expand All @@ -150,6 +150,6 @@ func (s *KeeperTestSuite) TestMsgSubmitQueryResponse_FindAndInvokeCallback_Wrong
// }

// tc.validMsg.ProofOps = proofOps
// err := s.App.InterchainqueryKeeper.VerifyKeyProof(s.Ctx(), &tc.validMsg, tc.query)
// err := s.App.InterchainqueryKeeper.VerifyKeyProof(s.Ctx, &tc.validMsg, tc.query)
// s.Require().NoError(err)
// }
2 changes: 1 addition & 1 deletion x/interchainquery/keeper/new_query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ func (s *KeeperTestSuite) TestNewQuerySuccessful() {
tc := s.SetupNewQuery()

actualQuery := s.App.InterchainqueryKeeper.NewQuery(
s.Ctx(),
s.Ctx,
tc.module,
tc.callbackId,
tc.chainId,
Expand Down
Loading

0 comments on commit 0e0238b

Please sign in to comment.