cosmos-sdk/client/context_test.go

103 lines
2.1 KiB
Go
Raw Normal View History

package client_test
import (
"bytes"
"os"
"testing"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/codec/types"
"github.com/cosmos/cosmos-sdk/testutil/testdata"
"github.com/cosmos/cosmos-sdk/crypto/keyring"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client"
"github.com/cosmos/cosmos-sdk/client/flags"
)
func TestMain(m *testing.M) {
viper.Set(flags.FlagKeyringBackend, keyring.BackendMemory)
os.Exit(m.Run())
}
func TestContext_PrintOutput(t *testing.T) {
ctx := client.Context{}
animal := &testdata.Dog{
Size_: "big",
Name: "Spot",
}
any, err := types.NewAnyWithValue(animal)
require.NoError(t, err)
hasAnimal := &testdata.HasAnimal{
Animal: any,
X: 10,
}
//
// proto
//
registry := testdata.NewTestInterfaceRegistry()
ctx = ctx.WithJSONMarshaler(codec.NewProtoCodec(registry))
// json
buf := &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "json"
err = ctx.PrintOutput(hasAnimal)
require.NoError(t, err)
require.Equal(t,
2020-07-01 08:26:29 -07:00
`{"animal":{"@type":"/testdata.Dog","size":"big","name":"Spot"},"x":"10"}
`, string(buf.Bytes()))
// yaml
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "text"
err = ctx.PrintOutput(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`animal:
2020-07-01 08:26:29 -07:00
'@type': /testdata.Dog
name: Spot
size: big
x: "10"
`, string(buf.Bytes()))
//
// amino
//
amino := testdata.NewTestAmino()
ctx = ctx.WithJSONMarshaler(codec.NewAminoCodec(&codec.Codec{Amino: amino}))
// json
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "json"
err = ctx.PrintOutput(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`{"type":"testdata/HasAnimal","value":{"animal":{"type":"testdata/Dog","value":{"size":"big","name":"Spot"}},"x":"10"}}
`, string(buf.Bytes()))
// yaml
buf = &bytes.Buffer{}
ctx = ctx.WithOutput(buf)
ctx.OutputFormat = "text"
err = ctx.PrintOutput(hasAnimal)
require.NoError(t, err)
require.Equal(t,
`type: testdata/HasAnimal
value:
animal:
type: testdata/Dog
value:
name: Spot
size: big
x: "10"
`, string(buf.Bytes()))
}