network

package
v0.0.0-...-fd76dfc Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 14, 2024 License: Apache-2.0 Imports: 28 Imported by: 2

README

Network Testing

The network package implements and exposes a fully operational in-process CometBFT test network that consists of at least one or potentially many validators. This test network can be used primarily for integration tests or unit test suites.

The test network utilizes SimApp as the ABCI application and uses all the modules defined in the Cosmos SDK. An in-process test network can be configured with any number of validators as well as account funds and even custom genesis state.

When creating a test network, a series of Validator objects are returned. Each Validator object has useful information such as their address and public key. A Validator will also provide its RPC, P2P, and API addresses that can be useful for integration testing. In addition, a CometBFT local RPC client is also provided which can be handy for making direct RPC calls to CometBFT.

Note, due to limitations in concurrency and the design of the RPC layer in CometBFT, only the first Validator object will have an RPC and API client exposed. Due to this exact same limitation, only a single test network can exist at a time. A caller must be certain it calls Cleanup after it no longer needs the network.

This package is extended from the Cosmos-SDK network testutil package. This package creates a simpler API for setting up your custom application for network testing.

A typical testing flow that extends the bank genesis state might look like the following:

    import (
        "math/rand"

        tmdb "github.com/cometbft/cometbft-db"
        tmrand "github.com/cometbft/cometbft/libs/rand"
        "github.com/cosmos/cosmos-sdk/baseapp"
        servertypes "github.com/cosmos/cosmos-sdk/server/types"
        banktypes "github.com/cosmos/cosmos-sdk/x/bank/types"
        pruningtypes "cosmossdk.io/store/pruning/types"
        simtestutil "github.com/cosmos/cosmos-sdk/testutil/sims"
        "github.com/cosmos/gogoproto/proto"

        "github.com/skip-mev/chaintestutil/network"
        "github.com/skip-mev/chaintestutil/sample"
        "github.com/stretchr/testify/require"   
        "github.com/stretchr/testify/suite"

        "github.com/test-repo/app" // example test repository. Replace with your own 		
    )

    var (
        chainID = "chain-" + tmrand.NewRand().Str(6)

        DefaultAppConstructor = func(val network.ValidatorI) servertypes.Application {
            return app.New(
                val.GetCtx().Logger,
                tmdb.NewMemDB(),
                nil,
                true,
                simtestutil.EmptyAppOptions{},
                baseapp.SetPruning(pruningtypes.NewPruningOptionsFromString(val.GetAppConfig().Pruning)),
                baseapp.SetMinGasPrices(val.GetAppConfig().MinGasPrices),
                baseapp.SetChainID(chainID),
            )
	    }
    )

    // NetworkTestSuite is a test suite for query tests that initializes a network instance. 
    type NetworkTestSuite struct {
        suite.Suite
		
        Network        *network.Network
        BankState banktypes.GenesisState
    }

    // SetupSuite setups the local network with a genesis state.
    func (nts *NetworkTestSuite) SetupSuite() {
            var (
                r   = sample.Rand()
                cfg = network.NewConfig(DefaultAppConstructor, app.ModuleBasics, chainID)
            )

            updateGenesisConfigState := func(moduleName string, moduleState proto.Message) {
            buf, err := cfg.Codec.MarshalJSON(moduleState)
            require.NoError(nts.T(), err)
            cfg.GenesisState[moduleName] = buf
        }

        // initialize new bank state
        require.NoError(nts.T(), cfg.Codec.UnmarshalJSON(cfg.GenesisState[banktypes.ModuleName], &nts.BankState))
        nts.BankState = populateBankState(r, nts.BankState)
        updateGenesisConfigState(banktypes.ModuleName, &nts.BankState)

        nts.Network = network.New(nts.T(), cfg)
    }

    func populateBankState(_ *rand.Rand, bankState banktypes.GenesisState) banktypes.GenesisState {
        // intercept and populate the state randomly if desired
		// ...
        return bankState
    }

	func (nts *NetworkTestSuite) TestQueryBalancesRequestHandlerFn() {
        val := s.network.Validators[0]
        baseURL := val.APIAddress

        // Use baseURL to make API HTTP requests or use val.RPCClient to make direct
        // CometBFT RPC calls.
        // ...
    }

    func TestNetworkTestSuite(t *testing.T) {
        suite.Run(t, new(NetworkTestSuite))
    }

Documentation

Overview

Package network allows to programmatically spin up a local network for CLI tests

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(t *testing.T, cfg network.Config) *network.Network

New creates instance with fully configured cosmos network. Accepts optional config, that will be used in place of the DefaultConfig() if provided.

func NewConfig

func NewConfig(appConfig depinject.Config) network.Config

NewConfig will initialize config for the network with custom application, genesis and single validator. All other parameters are inherited from cosmos-sdk/testutil/network.DefaultConfig

Types

type AppConstructor

type AppConstructor func(val ValidatorI) TestApp

type BroadcastMode

type BroadcastMode int

BroadcastMode is a type alias for Tx broadcast modes.

const (
	BroadcastModeSync BroadcastMode = iota
	BroadcastModeAsync
	BroadcastModeCommit
)

type Config

type Config = network.Config

type Network

type Network = network.Network

type TestApp

type TestApp interface {
	runtime.AppI
	servertypes.Application
}

type TestSuite

type TestSuite struct {
	Network *Network
}

TestSuite is a test suite for tests that initializes a network instance.

func NewSuite

func NewSuite(t *testing.T, cfg network.Config) *TestSuite

func (*TestSuite) AccountI

func (s *TestSuite) AccountI(acc account.Account) (sdk.AccountI, error)

func (*TestSuite) AllValidators

func (s *TestSuite) AllValidators() ([]stakingtypes.Validator, error)

func (*TestSuite) Balances

func (s *TestSuite) Balances(acc account.Account) (sdk.Coins, error)

func (*TestSuite) BroadcastTx

func (s *TestSuite) BroadcastTx(ctx context.Context, bz []byte, mode BroadcastMode) (*coretypes.ResultBroadcastTx, error)

BroadcastTx broadcasts the given Tx in sync or async mode and returns the result.

func (*TestSuite) BroadcastTxCommit

func (s *TestSuite) BroadcastTxCommit(ctx context.Context, bz []byte) (*coretypes.ResultBroadcastTxCommit, error)

BroadcastTxCommit broadcasts the given Tx in commit mode and returns the result.

func (*TestSuite) CreateTxBytes

func (s *TestSuite) CreateTxBytes(ctx context.Context, txGen TxGenInfo, msgs ...sdk.Msg) ([]byte, error)

CreateTxBytes creates and signs a transaction, from the given messages.

func (*TestSuite) CreateValidatorTxBytes

func (s *TestSuite) CreateValidatorTxBytes(fees sdk.Coin, gas uint64, msgs []sdk.Msg) ([]byte, error)

CreateValidatorTxBytes creates tx bytes using the first validators keyring.

func (*TestSuite) GetCometClient

func (s *TestSuite) GetCometClient() (*cmthttp.HTTP, error)

func (*TestSuite) GetGRPC

func (s *TestSuite) GetGRPC() (cc *grpc.ClientConn, close func(), err error)

GetGRPC returns a grpc client for the first validator's node.

func (*TestSuite) ValidatorDelegations

func (s *TestSuite) ValidatorDelegations(valAddr string) ([]stakingtypes.DelegationResponse, error)

func (*TestSuite) ValidatorDistributionInfo

func (s *TestSuite) ValidatorDistributionInfo(valAddr string) (*distrtypes.QueryValidatorDistributionInfoResponse, error)

type TxGenInfo

type TxGenInfo struct {
	Account       account.Account
	GasLimit      uint64
	TimeoutHeight uint64
	Fee           sdk.Coins
	// OverrideSequence will manually set the account sequence for signing using Sequence.
	OverrideSequence bool
	// Sequence is the account sequence to be used if OverrideSequence is true.
	Sequence uint64
}

TxGenInfo contains common info for generating transactions for tests.

type ValidatorI

type ValidatorI = network.ValidatorI

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL