Merge PR #3553: Code cleanup, take #1

* add a bunch of tests, add DONTCOVER text tag

- Also fix flaky test (closes: #3559). Don't test values
  returned by queries since there's no way to query a
  specific height via REST.

* GetTempDir -> NewTestCaseDir
This commit is contained in:
Alessio Treglia 2019-02-08 13:45:41 -08:00 committed by Christopher Goes
parent 2c9a5bc308
commit e7e3c32204
32 changed files with 225 additions and 102 deletions

View File

@ -232,6 +232,14 @@ jobs:
for prof in $(ls /tmp/workspace/profiles/); do
tail -n +2 /tmp/workspace/profiles/"$prof" >> coverage.txt
done
- run:
name: filter out DONTCOVER
command: |
excludelist="$(find ./ -type f -name '*.go' | xargs grep -l 'DONTCOVER' | xargs realpath --relative-to=$GOPATH/src)"
for filename in ${excludelist}; do
echo "Excluding ${filename} ..."
sed -i "\%${filename}:%d" coverage.txt
done
- run:
name: upload
command: bash <(curl -s https://codecov.io/bash) -f coverage.txt

View File

@ -10,7 +10,6 @@ import (
"strings"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
abci "github.com/tendermint/tendermint/abci/types"
"github.com/tendermint/tendermint/crypto/merkle"
cmn "github.com/tendermint/tendermint/libs/common"
@ -18,6 +17,8 @@ import (
tmliteProxy "github.com/tendermint/tendermint/lite/proxy"
rpcclient "github.com/tendermint/tendermint/rpc/client"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
)
// GetNode returns an RPC client. If the context's client is not defined, an

View File

@ -28,8 +28,7 @@ func Test_runAddCmdBasic(t *testing.T) {
assert.EqualError(t, err, "EOF")
// Prepare a keybase
kbHome, kbCleanUp, err := tests.GetTempDir("Test_runDeleteCmd")
assert.NoError(t, err)
kbHome, kbCleanUp := tests.NewTestCaseDir(t)
assert.NotNil(t, kbHome)
defer kbCleanUp()
viper.Set(cli.HomeFlag, kbHome)

View File

@ -26,8 +26,7 @@ func Test_runDeleteCmd(t *testing.T) {
fakeKeyName2 := "runDeleteCmd_Key2"
// Now add a temporary keybase
kbHome, cleanUp, err := tests.GetTempDir("Test_runDeleteCmd")
assert.NoError(t, err)
kbHome, cleanUp := tests.NewTestCaseDir(t)
defer cleanUp()
viper.Set(cli.HomeFlag, kbHome)

View File

@ -21,15 +21,13 @@ func Test_runListCmd(t *testing.T) {
cmdBasic := listKeysCmd()
// Prepare some keybases
kbHome1, cleanUp1, err := tests.GetTempDir("Test_runListCmd")
kbHome1, cleanUp1 := tests.NewTestCaseDir(t)
defer cleanUp1()
assert.NoError(t, err)
// Do nothing, leave home1 empty
kbHome2, cleanUp2, err := tests.GetTempDir("Test_runListCmd")
kbHome2, cleanUp2 := tests.NewTestCaseDir(t)
defer cleanUp2()
viper.Set(cli.HomeFlag, kbHome2)
assert.NoError(t, err)
kb, err := NewKeyBaseFromHomeFlag()
assert.NoError(t, err)

View File

@ -5,8 +5,9 @@ import (
"fmt"
bip39 "github.com/bartekn/go-bip39"
"github.com/cosmos/cosmos-sdk/client"
"github.com/spf13/cobra"
"github.com/cosmos/cosmos-sdk/client"
)
const (

View File

@ -46,8 +46,7 @@ func Test_runShowCmd(t *testing.T) {
// Prepare a key base
// Now add a temporary keybase
kbHome, cleanUp, err := tests.GetTempDir("Test_runShowCmd")
assert.NoError(t, err)
kbHome, cleanUp := tests.NewTestCaseDir(t)
defer cleanUp()
viper.Set(cli.HomeFlag, kbHome)

View File

@ -39,8 +39,7 @@ func Test_runUpdateCmd(t *testing.T) {
// Prepare a key base
// Now add a temporary keybase
kbHome, cleanUp1, err := tests.GetTempDir("Test_runShowCmd")
assert.NoError(t, err)
kbHome, cleanUp1 := tests.NewTestCaseDir(t)
defer cleanUp1()
viper.Set(cli.HomeFlag, kbHome)

View File

@ -568,7 +568,8 @@ func TestBonding(t *testing.T) {
require.NoError(t, err)
addr, _ := CreateAddr(t, name1, pw, kb)
cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 2, []sdk.AccAddress{addr}, true)
cleanup, valPubKeys, operAddrs, port := InitializeTestLCD(t, 2, []sdk.AccAddress{addr}, false)
tests.WaitForHeight(1, port)
defer cleanup()
require.Equal(t, 2, len(valPubKeys))
@ -1066,7 +1067,7 @@ func TestDistributionFlow(t *testing.T) {
kb, err := keys.NewKeyBaseFromDir(InitClientHome(t, ""))
require.NoError(t, err)
addr, seed := CreateAddr(t, name1, pw, kb)
cleanup, _, valAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, false)
cleanup, _, valAddrs, port := InitializeTestLCD(t, 1, []sdk.AccAddress{addr}, true)
defer cleanup()
valAddr := valAddrs[0]
@ -1076,15 +1077,12 @@ func TestDistributionFlow(t *testing.T) {
res, body := Request(t, port, "GET", fmt.Sprintf("/distribution/outstanding_rewards"), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, sdk.DecCoins(nil), rewards)
var valDistInfo distrrest.ValidatorDistInfo
res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &valDistInfo))
require.Equal(t, valDistInfo.OperatorAddress.String(), sdk.AccAddress(valAddr).String())
require.Equal(t, valDistInfo.ValidatorCommission, sdk.DecCoins(nil))
require.Equal(t, valDistInfo.SelfBondRewards, sdk.DecCoins(nil))
// Delegate some coins
delTokens := staking.TokensFromTendermintPower(60)
@ -1098,43 +1096,35 @@ func TestDistributionFlow(t *testing.T) {
require.Equal(t, uint32(0), resultTx.Code)
// Query outstanding rewards changed
oustandingRewards := mustParseDecCoins("9.80stake")
res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/outstanding_rewards"), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, oustandingRewards, rewards)
// Query validator distribution info
res, body = Request(t, port, "GET", "/distribution/validators/"+valAddr.String(), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
valRewards := mustParseDecCoins("6.125stake")
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &valDistInfo))
require.Equal(t, valRewards, valDistInfo.SelfBondRewards)
// Query validator's rewards
res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/validators/%s/rewards", valAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, valRewards, rewards)
// Query self-delegation
res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", operAddr, valAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, valRewards, rewards)
// Query delegation
res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards/%s", addr, valAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, mustParseDecCoins("3.675stake"), rewards)
// Query delegator's rewards total
res, body = Request(t, port, "GET", fmt.Sprintf("/distribution/delegators/%s/rewards", operAddr), nil)
require.Equal(t, http.StatusOK, res.StatusCode, body)
require.NoError(t, cdc.UnmarshalJSON([]byte(body), &rewards))
require.Equal(t, valRewards, rewards)
// Query delegator's withdrawal address
var withdrawAddr string

View File

@ -417,10 +417,7 @@ func TestGaiaImportExport(t *testing.T) {
fmt.Printf("Exporting genesis...\n")
appState, _, err := app.ExportAppStateAndValidators(false, []string{})
if err != nil {
panic(err)
}
require.NoError(t, err)
fmt.Printf("Importing genesis...\n")
newDir, _ := ioutil.TempDir("", "goleveldb-gaia-sim-2")

View File

@ -1,5 +1,7 @@
package init
// DONTCOVER
import (
"encoding/json"
"path/filepath"

View File

@ -1,5 +1,7 @@
package init
// DONTCOVER
import (
"bytes"
"fmt"

View File

@ -79,7 +79,6 @@ func TestEmptyState(t *testing.T) {
w.Close()
os.Stdout = old
out := <-outC
require.Contains(t, out, "WARNING: State is not initialized")
require.Contains(t, out, "genesis_time")
require.Contains(t, out, "chain_id")
require.Contains(t, out, "consensus_params")

View File

@ -1,5 +1,7 @@
package init
// DONTCOVER
import (
"encoding/json"
"fmt"

View File

@ -0,0 +1,49 @@
package init
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"testing"
"time"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/tests"
"github.com/stretchr/testify/require"
)
func TestExportGenesisFileWithTime(t *testing.T) {
t.Parallel()
dir, cleanup := tests.NewTestCaseDir(t)
defer cleanup()
fname := filepath.Join(dir, "genesis.json")
require.NoError(t, ExportGenesisFileWithTime(fname, "test", nil, json.RawMessage(""), time.Now()))
}
func TestLoadGenesisDoc(t *testing.T) {
t.Parallel()
dir, cleanup := tests.NewTestCaseDir(t)
defer cleanup()
fname := filepath.Join(dir, "genesis.json")
require.NoError(t, ExportGenesisFileWithTime(fname, "test", nil, json.RawMessage(""), time.Now()))
_, err := LoadGenesisDoc(codec.Cdc, fname)
require.NoError(t, err)
// Non-existing file
_, err = LoadGenesisDoc(codec.Cdc, "non-existing-file")
require.Error(t, err)
malformedFilename := filepath.Join(dir, "malformed")
malformedFile, err := os.Create(malformedFilename)
require.NoError(t, err)
fmt.Fprint(malformedFile, "invalidjson")
malformedFile.Close()
// Non-existing file
_, err = LoadGenesisDoc(codec.Cdc, malformedFilename)
require.Error(t, err)
}

View File

@ -1,10 +1,11 @@
package keys
import (
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
"github.com/cosmos/cosmos-sdk/types"
"github.com/tendermint/tendermint/crypto"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
"github.com/cosmos/cosmos-sdk/types"
)
var _ Keybase = lazyKeybase{}

View File

@ -5,11 +5,12 @@ import (
"os"
"github.com/btcsuite/btcd/btcec"
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
"github.com/pkg/errors"
tmbtcec "github.com/tendermint/btcd/btcec"
tmcrypto "github.com/tendermint/tendermint/crypto"
tmsecp256k1 "github.com/tendermint/tendermint/crypto/secp256k1"
"github.com/cosmos/cosmos-sdk/crypto/keys/hd"
)
var (

View File

@ -0,0 +1,33 @@
package server
import (
"path/filepath"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/tests"
)
func Test_openDB(t *testing.T) {
t.Parallel()
dir, cleanup := tests.NewTestCaseDir(t)
defer cleanup()
_, err := openDB(dir)
require.NoError(t, err)
}
func Test_openTraceWriter(t *testing.T) {
t.Parallel()
dir, cleanup := tests.NewTestCaseDir(t)
defer cleanup()
fname := filepath.Join(dir, "logfile")
w, err := openTraceWriter(fname)
require.NoError(t, err)
require.NotNil(t, w)
// test no-op
w, err = openTraceWriter("")
require.NoError(t, err)
require.Nil(t, w)
}

View File

@ -1,7 +1,10 @@
package server
// DONTCOVER
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
@ -9,6 +12,7 @@ import (
"io/ioutil"
"path"
"github.com/tendermint/tendermint/libs/cli"
tmtypes "github.com/tendermint/tendermint/types"
"github.com/cosmos/cosmos-sdk/codec"
@ -26,17 +30,18 @@ func ExportCmd(ctx *Context, cdc *codec.Codec, appExporter AppExporter) *cobra.C
Use: "export",
Short: "Export state to JSON",
RunE: func(cmd *cobra.Command, args []string) error {
home := viper.GetString("home")
config := ctx.Config
config.SetRoot(viper.GetString(cli.HomeFlag))
traceWriterFile := viper.GetString(flagTraceStore)
emptyState, err := isEmptyState(home)
emptyState, err := isEmptyState(config.RootDir)
if err != nil {
return err
}
if emptyState || appExporter == nil {
fmt.Println("WARNING: State is not initialized. Returning genesis file.")
genesisFile := path.Join(home, "config", "genesis.json")
genesis, err := ioutil.ReadFile(genesisFile)
fmt.Fprintln(os.Stderr, "WARNING: State is not initialized. Returning genesis file.")
genesis, err := ioutil.ReadFile(config.GenesisFile())
if err != nil {
return err
}
@ -44,7 +49,7 @@ func ExportCmd(ctx *Context, cdc *codec.Codec, appExporter AppExporter) *cobra.C
return nil
}
db, err := openDB(home)
db, err := openDB(config.RootDir)
if err != nil {
return err
}

View File

@ -5,12 +5,14 @@ import (
"os"
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client/keys"
"github.com/cosmos/cosmos-sdk/server"
"github.com/stretchr/testify/require"
)
func TestGenerateCoinKey(t *testing.T) {
t.Parallel()
addr, mnemonic, err := server.GenerateCoinKey()
require.NoError(t, err)
@ -21,6 +23,7 @@ func TestGenerateCoinKey(t *testing.T) {
}
func TestGenerateSaveCoinKey(t *testing.T) {
t.Parallel()
dir, cleanup := tempdir(t)
defer cleanup() // clean after itself
// Remove the dir to that GenerateSaveCoinKey creates it automatically
@ -42,6 +45,28 @@ func TestGenerateSaveCoinKey(t *testing.T) {
require.Equal(t, addr, info.GetAddress())
}
func TestGenerateSaveCoinKeyOverwriteFlag(t *testing.T) {
t.Parallel()
dir, cleanup := tempdir(t)
defer cleanup() // clean after itself
// Remove the dir to that GenerateSaveCoinKey creates it automatically
os.RemoveAll(dir)
keyname := "justakey"
addr1, _, err := server.GenerateSaveCoinKey(dir, keyname, "012345678", false)
require.NoError(t, err)
// Test overwrite with overwrite=false
_, _, err = server.GenerateSaveCoinKey(dir, keyname, "012345678", false)
require.Error(t, err)
// Test overwrite with overwrite=true
addr2, _, err := server.GenerateSaveCoinKey(dir, keyname, "012345678", true)
require.NoError(t, err)
require.NotEqual(t, addr1, addr2)
}
func tempdir(t *testing.T) (string, func()) {
dir, err := ioutil.TempDir("", t.Name()+"_")
require.NoError(t, err)

View File

@ -1,5 +1,7 @@
package server
// DONTCOVER
import (
"fmt"

View File

@ -9,10 +9,11 @@ import (
abci "github.com/tendermint/tendermint/abci/types"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/cosmos/cosmos-sdk/store/rootmulti"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/stretchr/testify/require"
)
type TestStruct struct {

View File

@ -1,9 +1,10 @@
package transient
import (
"github.com/cosmos/cosmos-sdk/store/types"
dbm "github.com/tendermint/tendermint/libs/db"
"github.com/cosmos/cosmos-sdk/store/types"
"github.com/cosmos/cosmos-sdk/store/dbadapter"
)

View File

@ -5,8 +5,11 @@ import (
"io/ioutil"
"net/http"
"os"
"testing"
"time"
"github.com/stretchr/testify/require"
"strings"
amino "github.com/tendermint/go-amino"
@ -197,26 +200,17 @@ func ExtractPortFromAddress(listenAddress string) string {
return stringList[2]
}
// NewTestCaseDir creates a new temporary directory for a test case.
// Returns the directory path and a cleanup function.
// nolint: errcheck
func NewTestCaseDir(t *testing.T) (string, func()) {
dir, err := ioutil.TempDir("", t.Name()+"_")
require.NoError(t, err)
return dir, func() { os.RemoveAll(dir) }
}
var cdc = amino.NewCodec()
func init() {
ctypes.RegisterAmino(cdc)
}
// GetTempDir creates a temporary directory and returns a clean up function
// to be deferred
func GetTempDir(prefix string) (string, func(), error) {
rootDir, err := ioutil.TempDir("", prefix)
if err != nil {
return "", nil, err
}
cleanUp := func() {
err := os.RemoveAll(rootDir)
if err != nil {
panic(err)
}
}
return rootDir, cleanUp, nil
}

View File

@ -22,7 +22,7 @@ import (
var (
flagOnlyFromValidator = "only-from-validator"
flagIsValidator = "is-validator"
flagComission = "comission"
flagComission = "commission"
)
// GetTxCmd returns the transaction commands for this module
@ -48,7 +48,7 @@ func GetCmdWithdrawRewards(cdc *codec.Codec) *cobra.Command {
Long: strings.TrimSpace(`witdraw rewards from a given delegation address, and optionally withdraw validator commission if the delegation address given is a validator operator:
$ gaiacli tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey
$ gaiacli tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --comission
$ gaiacli tx distr withdraw-rewards cosmosvaloper1gghjut3ccd8ay0zduzj64hwre2fxs9ldmqhffj --from mykey --commission
`),
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
@ -108,7 +108,7 @@ func GetCmdSetWithdrawAddr(cdc *codec.Codec) *cobra.Command {
cmd := &cobra.Command{
Use: "set-withdraw-addr [withdraw-addr]",
Short: "change the default withdraw address for rewards associated with an address",
Long: strings.TrimSpace(`Set the withdraw address for rewards assoicated with a delegator address:
Long: strings.TrimSpace(`Set the withdraw address for rewards associated with a delegator address:
$ gaiacli tx set-withdraw-addr cosmos1gghjut3ccd8ay0zduzj64hwre2fxs9ld75ru9p --from mykey
`),

View File

@ -3,9 +3,10 @@ package common
import (
"testing"
"github.com/stretchr/testify/require"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/stretchr/testify/require"
)
func TestQueryDelegationRewardsAddrValidation(t *testing.T) {

View File

@ -8,11 +8,12 @@ import (
"github.com/cosmos/cosmos-sdk/x/distribution/client/common"
"github.com/cosmos/cosmos-sdk/x/distribution/types"
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/client/rest"
"github.com/cosmos/cosmos-sdk/codec"
sdk "github.com/cosmos/cosmos-sdk/types"
"github.com/gorilla/mux"
)
func registerQueryRoutes(cliCtx context.CLIContext, r *mux.Router,

View File

@ -1,9 +1,10 @@
package rest
import (
"github.com/gorilla/mux"
"github.com/cosmos/cosmos-sdk/client/context"
"github.com/cosmos/cosmos-sdk/codec"
"github.com/gorilla/mux"
)
// RegisterRoutes register distribution REST routes.

42
x/gov/client/cli/parse.go Normal file
View File

@ -0,0 +1,42 @@
package cli
import (
"encoding/json"
"fmt"
"io/ioutil"
"github.com/spf13/viper"
govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils"
)
func parseSubmitProposalFlags() (*proposal, error) {
proposal := &proposal{}
proposalFile := viper.GetString(flagProposal)
if proposalFile == "" {
proposal.Title = viper.GetString(flagTitle)
proposal.Description = viper.GetString(flagDescription)
proposal.Type = govClientUtils.NormalizeProposalType(viper.GetString(flagProposalType))
proposal.Deposit = viper.GetString(flagDeposit)
return proposal, nil
}
for _, flag := range proposalFlags {
if viper.GetString(flag) != "" {
return nil, fmt.Errorf("--%s flag provided alongside --proposal, which is a noop", flag)
}
}
contents, err := ioutil.ReadFile(proposalFile)
if err != nil {
return nil, err
}
err = json.Unmarshal(contents, proposal)
if err != nil {
return nil, err
}
return proposal, nil
}

View File

@ -511,3 +511,5 @@ $ gaiacli query gov proposer 1
},
}
}
// DONTCOVER

View File

@ -11,12 +11,9 @@ import (
authtxb "github.com/cosmos/cosmos-sdk/x/auth/client/txbuilder"
"github.com/cosmos/cosmos-sdk/x/gov"
"encoding/json"
"io/ioutil"
"strings"
"github.com/spf13/cobra"
"github.com/spf13/viper"
govClientUtils "github.com/cosmos/cosmos-sdk/x/gov/client/utils"
)
@ -126,37 +123,6 @@ $ gaiacli gov submit-proposal --title="Test Proposal" --description="My awesome
return cmd
}
func parseSubmitProposalFlags() (*proposal, error) {
proposal := &proposal{}
proposalFile := viper.GetString(flagProposal)
if proposalFile == "" {
proposal.Title = viper.GetString(flagTitle)
proposal.Description = viper.GetString(flagDescription)
proposal.Type = govClientUtils.NormalizeProposalType(viper.GetString(flagProposalType))
proposal.Deposit = viper.GetString(flagDeposit)
return proposal, nil
}
for _, flag := range proposalFlags {
if viper.GetString(flag) != "" {
return nil, fmt.Errorf("--%s flag provided alongside --proposal, which is a noop", flag)
}
}
contents, err := ioutil.ReadFile(proposalFile)
if err != nil {
return nil, err
}
err = json.Unmarshal(contents, proposal)
if err != nil {
return nil, err
}
return proposal, nil
}
// GetCmdDeposit implements depositing tokens for an active proposal.
func GetCmdDeposit(queryRoute string, cdc *codec.Codec) *cobra.Command {
return &cobra.Command{
@ -265,3 +231,5 @@ $ gaiacli tx gov vote 1 yes --from mykey
},
}
}
// DONTCOVER