cosmos-sdk/server/test_helpers.go

55 lines
1.1 KiB
Go
Raw Normal View History

2018-03-10 09:27:21 -08:00
package server
import (
"fmt"
"github.com/cosmos/cosmos-sdk/client"
2018-03-10 09:27:21 -08:00
"io/ioutil"
"net"
"os"
"testing"
"github.com/spf13/viper"
"github.com/stretchr/testify/require"
"github.com/tendermint/tendermint/libs/cli"
2018-03-10 09:27:21 -08:00
)
// Get a free address for a test tendermint server
2018-03-12 08:31:27 -07:00
// protocol is either tcp, http, etc
func FreeTCPAddr() (addr, port string, err error) {
2018-03-10 09:27:21 -08:00
l, err := net.Listen("tcp", "0.0.0.0:0")
if err != nil {
return "", "", err
}
closer := func() {
err := l.Close()
if err != nil {
// TODO: Handle with #870
panic(err)
}
}
defer closer()
2018-03-10 09:27:21 -08:00
portI := l.Addr().(*net.TCPAddr).Port
port = fmt.Sprintf("%d", portI)
addr = fmt.Sprintf("tcp://0.0.0.0:%s", port)
return
2018-03-10 09:27:21 -08:00
}
// SetupViper creates a homedir to run inside,
2018-03-10 09:27:21 -08:00
// and returns a cleanup function to defer
func SetupViper(t *testing.T) func() {
2018-03-10 09:27:21 -08:00
rootDir, err := ioutil.TempDir("", "mock-sdk-cmd")
require.Nil(t, err)
viper.Set(cli.HomeFlag, rootDir)
viper.Set(client.FlagName, "moniker")
2018-03-10 09:27:21 -08:00
return func() {
err := os.RemoveAll(rootDir)
if err != nil {
// TODO: Handle with #870
panic(err)
}
2018-03-10 09:27:21 -08:00
}
}