cosmos-sdk/x/mock/simulation/random_simulate_blocks.go

73 lines
2.1 KiB
Go
Raw Normal View History

2018-07-16 18:25:15 -07:00
package simulation
import (
"fmt"
"math/rand"
"testing"
"time"
2018-07-16 18:15:50 -07:00
"github.com/cosmos/cosmos-sdk/baseapp"
2018-07-16 18:25:15 -07:00
"github.com/cosmos/cosmos-sdk/x/mock"
"github.com/stretchr/testify/require"
abci "github.com/tendermint/tendermint/abci/types"
)
// RandomizedTesting tests application by sending random messages.
2018-07-16 18:15:50 -07:00
func RandomizedTesting(
t *testing.T, app *baseapp.BaseApp, ops []TestAndRunTx, setups []RandSetup,
invariants []Invariant, numKeys int, numBlocks int, blockSize int,
) {
time := time.Now().UnixNano()
2018-07-16 18:15:50 -07:00
RandomizedTestingFromSeed(t, app, time, ops, setups, invariants, numKeys, numBlocks, blockSize)
}
// RandomizedTestingFromSeed tests an application by running the provided
// operations, testing the provided invariants, but using the provided seed.
2018-07-16 18:15:50 -07:00
func RandomizedTestingFromSeed(
t *testing.T, app *baseapp.BaseApp, seed int64, ops []TestAndRunTx, setups []RandSetup,
invariants []Invariant, numKeys int, numBlocks int, blockSize int,
) {
log := fmt.Sprintf("Starting SingleModuleTest with randomness created with seed %d", int(seed))
2018-07-16 18:25:15 -07:00
keys, _ := mock.GeneratePrivKeyAddressPairs(numKeys)
r := rand.New(rand.NewSource(seed))
2018-07-16 18:15:50 -07:00
// XXX TODO
// RandomSetGenesis(r, app, addrs, []string{"foocoin"})
2018-07-10 11:46:28 -07:00
app.InitChain(abci.RequestInitChain{})
for i := 0; i < len(setups); i++ {
setups[i](r, keys)
}
2018-07-10 11:46:28 -07:00
app.Commit()
header := abci.Header{Height: 0}
for i := 0; i < numBlocks; i++ {
app.BeginBlock(abci.RequestBeginBlock{})
// Make sure invariants hold at beginning of block and when nothing was
// done.
2018-07-16 18:15:50 -07:00
AssertAllInvariants(t, app, invariants, log)
ctx := app.NewContext(false, header)
// TODO: Add modes to simulate "no load", "medium load", and
// "high load" blocks.
for j := 0; j < blockSize; j++ {
logUpdate, err := ops[r.Intn(len(ops))](t, r, app, ctx, keys, log)
log += "\n" + logUpdate
require.Nil(t, err, log)
2018-07-16 18:15:50 -07:00
AssertAllInvariants(t, app, invariants, log)
}
app.EndBlock(abci.RequestEndBlock{})
header.Height++
}
}
2018-07-16 18:15:50 -07:00
func AssertAllInvariants(t *testing.T, app *baseapp.BaseApp, tests []Invariant, log string) {
for i := 0; i < len(tests); i++ {
tests[i](t, app, log)
}
}