cosmos-sdk/types/result_test.go

254 lines
5.9 KiB
Go
Raw Normal View History

package types_test
import (
"encoding/hex"
"fmt"
"strings"
"testing"
"github.com/golang/protobuf/proto"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/libs/bytes"
"github.com/tendermint/tendermint/rpc/coretypes"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
sdk "github.com/cosmos/cosmos-sdk/types"
)
type resultTestSuite struct {
suite.Suite
}
func TestResultTestSuite(t *testing.T) {
suite.Run(t, new(resultTestSuite))
}
func (s *resultTestSuite) SetupSuite() {
s.T().Parallel()
}
func (s *resultTestSuite) TestParseABCILog() {
logs := `[{"log":"","msg_index":1,"success":true}]`
res, err := sdk.ParseABCILogs(logs)
s.Require().NoError(err)
s.Require().Len(res, 1)
s.Require().Equal(res[0].Log, "")
s.Require().Equal(res[0].MsgIndex, uint32(1))
}
func (s *resultTestSuite) TestABCIMessageLog() {
cdc := codec.NewLegacyAmino()
events := sdk.Events{sdk.NewEvent("transfer", sdk.NewAttribute("sender", "foo"))}
msgLog := sdk.NewABCIMessageLog(0, "", events)
msgLogs := sdk.ABCIMessageLogs{msgLog}
bz, err := cdc.MarshalJSON(msgLogs)
s.Require().NoError(err)
s.Require().Equal(string(bz), msgLogs.String())
}
func (s *resultTestSuite) TestNewSearchTxsResult() {
got := sdk.NewSearchTxsResult(150, 20, 2, 20, []*sdk.TxResponse{})
s.Require().Equal(&sdk.SearchTxsResult{
TotalCount: 150,
Count: 20,
PageNumber: 2,
PageTotal: 8,
Limit: 20,
Txs: []*sdk.TxResponse{},
}, got)
}
func (s *resultTestSuite) TestResponseResultTx() {
deliverTxResult := abci.ResponseDeliverTx{
Codespace: "codespace",
Code: 1,
Data: []byte("data"),
Log: `[]`,
Info: "info",
GasWanted: 100,
GasUsed: 90,
}
resultTx := &coretypes.ResultTx{
Hash: bytes.HexBytes([]byte("test")),
Height: 10,
TxResult: deliverTxResult,
}
logs, err := sdk.ParseABCILogs(`[]`)
s.Require().NoError(err)
want := &sdk.TxResponse{
TxHash: "74657374",
Height: 10,
Codespace: "codespace",
Code: 1,
Data: strings.ToUpper(hex.EncodeToString([]byte("data"))),
RawLog: `[]`,
Logs: logs,
Info: "info",
GasWanted: 100,
GasUsed: 90,
Tx: nil,
Timestamp: "timestamp",
}
s.Require().Equal(want, sdk.NewResponseResultTx(resultTx, nil, "timestamp"))
s.Require().Equal((*sdk.TxResponse)(nil), sdk.NewResponseResultTx(nil, nil, "timestamp"))
2021-11-30 07:29:09 -08:00
s.Require().Equal(`code: 1
codespace: codespace
data: "64617461"
events: []
gas_used: "90"
gas_wanted: "100"
height: "10"
info: info
logs: []
raw_log: '[]'
timestamp: timestamp
tx: null
txhash: "74657374"
`, sdk.NewResponseResultTx(resultTx, nil, "timestamp").String())
s.Require().True(sdk.TxResponse{}.Empty())
s.Require().False(want.Empty())
resultBroadcastTx := &coretypes.ResultBroadcastTx{
Code: 1,
Codespace: "codespace",
Data: []byte("data"),
Log: `[]`,
Hash: bytes.HexBytes([]byte("test")),
}
s.Require().Equal(&sdk.TxResponse{
Code: 1,
Codespace: "codespace",
Data: "64617461",
RawLog: `[]`,
Logs: logs,
TxHash: "74657374",
}, sdk.NewResponseFormatBroadcastTx(resultBroadcastTx))
s.Require().Equal((*sdk.TxResponse)(nil), sdk.NewResponseFormatBroadcastTx(nil))
}
func (s *resultTestSuite) TestResponseFormatBroadcastTxCommit() {
// test nil
s.Require().Equal((*sdk.TxResponse)(nil), sdk.NewResponseFormatBroadcastTxCommit(nil))
logs, err := sdk.ParseABCILogs(`[]`)
s.Require().NoError(err)
// test checkTx
checkTxResult := &coretypes.ResultBroadcastTxCommit{
Height: 10,
Hash: bytes.HexBytes([]byte("test")),
CheckTx: abci.ResponseCheckTx{
Code: 90,
Data: nil,
Log: `[]`,
Info: "info",
GasWanted: 99,
GasUsed: 100,
Codespace: "codespace",
2021-11-30 07:29:09 -08:00
Events: []abci.Event{
{
Type: "message",
Attributes: []abci.EventAttribute{
{
Key: "action",
Value: "foo",
Index: true,
},
},
},
},
},
}
deliverTxResult := &coretypes.ResultBroadcastTxCommit{
Height: 10,
Hash: bytes.HexBytes([]byte("test")),
DeliverTx: abci.ResponseDeliverTx{
Code: 90,
Data: nil,
Log: `[]`,
Info: "info",
GasWanted: 99,
GasUsed: 100,
Codespace: "codespace",
2021-11-30 07:29:09 -08:00
Events: []abci.Event{
{
Type: "message",
Attributes: []abci.EventAttribute{
{
Key: "action",
Value: "foo",
Index: true,
},
},
},
},
},
}
want := &sdk.TxResponse{
Height: 10,
TxHash: "74657374",
Codespace: "codespace",
Code: 90,
Data: "",
RawLog: `[]`,
Logs: logs,
Info: "info",
GasWanted: 99,
GasUsed: 100,
2021-11-30 07:29:09 -08:00
Events: []abci.Event{
{
Type: "message",
Attributes: []abci.EventAttribute{
{
Key: "action",
Value: "foo",
Index: true,
},
},
},
},
}
s.Require().Equal(want, sdk.NewResponseFormatBroadcastTxCommit(checkTxResult))
s.Require().Equal(want, sdk.NewResponseFormatBroadcastTxCommit(deliverTxResult))
}
func TestWrapServiceResult(t *testing.T) {
ctx := sdk.Context{}
res, err := sdk.WrapServiceResult(ctx, nil, fmt.Errorf("test"))
require.Nil(t, res)
require.NotNil(t, err)
refactor: middleware refactor to change tx.Handler interface (#10527) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Closes: #10484 This PR makes the following big changes: ### 1. Change the tx.Handler interface ```diff - CheckTx(ctx context.Context, tx sdk.Tx, req abci.RequestCheckTx) (abci.ResponseCheckTx, error) + CheckTx(ctx context.Context, req tx.Request, checkReq tx.RequestCheckTx) (tx.Response, tx.ResponseCheckTx, error) // same for Deliver and Simulate ``` where: ```go type Response struct { GasWanted uint64 GasUsed uint64 // MsgResponses is an array containing each Msg service handler's response // type, packed in an Any. This will get proto-serialized into the `Data` field // in the ABCI Check/DeliverTx responses. MsgResponses []*codectypes.Any Log string Events []abci.Event } ``` ### 2. Change what gets passed into the ABCI Check/DeliverTx `Data` field Before, we were passing the concatenation of MsgResponse bytes into the `Data`. Now we are passing the proto-serialiazation of this struct: ```proto message TxMsgData { repeated google.protobuf.Any msg_responses = 2; } ``` <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-12-01 22:54:38 -08:00
res, err = sdk.WrapServiceResult(ctx, &testdata.Dog{}, nil)
require.NotNil(t, res)
require.Nil(t, err)
require.Empty(t, res.Events)
ctx = ctx.WithEventManager(sdk.NewEventManager())
ctx.EventManager().EmitEvent(sdk.NewEvent("test"))
refactor: middleware refactor to change tx.Handler interface (#10527) <!-- The default pull request template is for types feat, fix, or refactor. For other templates, add one of the following parameters to the url: - template=docs.md - template=other.md --> ## Description Closes: #10484 This PR makes the following big changes: ### 1. Change the tx.Handler interface ```diff - CheckTx(ctx context.Context, tx sdk.Tx, req abci.RequestCheckTx) (abci.ResponseCheckTx, error) + CheckTx(ctx context.Context, req tx.Request, checkReq tx.RequestCheckTx) (tx.Response, tx.ResponseCheckTx, error) // same for Deliver and Simulate ``` where: ```go type Response struct { GasWanted uint64 GasUsed uint64 // MsgResponses is an array containing each Msg service handler's response // type, packed in an Any. This will get proto-serialized into the `Data` field // in the ABCI Check/DeliverTx responses. MsgResponses []*codectypes.Any Log string Events []abci.Event } ``` ### 2. Change what gets passed into the ABCI Check/DeliverTx `Data` field Before, we were passing the concatenation of MsgResponse bytes into the `Data`. Now we are passing the proto-serialiazation of this struct: ```proto message TxMsgData { repeated google.protobuf.Any msg_responses = 2; } ``` <!-- Add a description of the changes that this PR introduces and the files that are the most critical to review. --> --- ### Author Checklist *All items are required. Please add a note to the item if the item is not applicable and please add links to any relevant follow up issues.* I have... - [ ] included the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] added `!` to the type prefix if API or client breaking change - [ ] targeted the correct branch (see [PR Targeting](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#pr-targeting)) - [ ] provided a link to the relevant issue or specification - [ ] followed the guidelines for [building modules](https://github.com/cosmos/cosmos-sdk/blob/master/docs/building-modules) - [ ] included the necessary unit and integration [tests](https://github.com/cosmos/cosmos-sdk/blob/master/CONTRIBUTING.md#testing) - [ ] added a changelog entry to `CHANGELOG.md` - [ ] included comments for [documenting Go code](https://blog.golang.org/godoc) - [ ] updated the relevant documentation or specification - [ ] reviewed "Files changed" and left comments if necessary - [ ] confirmed all CI checks have passed ### Reviewers Checklist *All items are required. Please add a note if the item is not applicable and please add your handle next to the items reviewed if you only reviewed selected items.* I have... - [ ] confirmed the correct [type prefix](https://github.com/commitizen/conventional-commit-types/blob/v3.0.0/index.json) in the PR title - [ ] confirmed `!` in the type prefix if API or client breaking change - [ ] confirmed all author checklist items have been addressed - [ ] reviewed state machine logic - [ ] reviewed API design and naming - [ ] reviewed documentation is accurate - [ ] reviewed tests and test coverage - [ ] manually tested (if applicable)
2021-12-01 22:54:38 -08:00
res, err = sdk.WrapServiceResult(ctx, &testdata.Dog{}, nil)
require.NotNil(t, res)
require.Nil(t, err)
require.Len(t, res.Events, 1)
spot := testdata.Dog{Name: "spot"}
res, err = sdk.WrapServiceResult(ctx, &spot, nil)
require.NotNil(t, res)
require.Nil(t, err)
require.Len(t, res.Events, 1)
var spot2 testdata.Dog
err = proto.Unmarshal(res.Data, &spot2)
require.NoError(t, err)
require.Equal(t, spot, spot2)
}