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

74 lines
2.3 KiB
Go
Raw Normal View History

2018-07-16 18:25:15 -07:00
package simulation
import (
2018-07-17 11:33:53 -07:00
"encoding/json"
"fmt"
"math/rand"
"testing"
"time"
2018-07-16 18:15:50 -07:00
"github.com/cosmos/cosmos-sdk/baseapp"
2018-07-17 15:04:10 -07:00
sdk "github.com/cosmos/cosmos-sdk/types"
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"
)
2018-07-17 11:33:53 -07:00
// Simulate tests application by sending random messages.
func Simulate(
2018-07-17 15:04:10 -07:00
t *testing.T, app *baseapp.BaseApp, appStateFn func(r *rand.Rand, accs []sdk.AccAddress) json.RawMessage, ops []TestAndRunTx, setups []RandSetup,
invariants []Invariant, numKeys int, numBlocks int, blockSize int,
) {
time := time.Now().UnixNano()
2018-07-17 15:04:10 -07:00
SimulateFromSeed(t, app, appStateFn, time, ops, setups, invariants, numKeys, numBlocks, blockSize)
}
2018-07-17 11:33:53 -07:00
// SimulateFromSeed tests an application by running the provided
// operations, testing the provided invariants, but using the provided seed.
2018-07-17 11:33:53 -07:00
func SimulateFromSeed(
2018-07-17 15:04:10 -07:00
t *testing.T, app *baseapp.BaseApp, appStateFn func(r *rand.Rand, accs []sdk.AccAddress) json.RawMessage, seed int64, ops []TestAndRunTx, setups []RandSetup,
invariants []Invariant, numKeys int, numBlocks int, blockSize int,
) {
2018-07-17 15:04:10 -07:00
log := fmt.Sprintf("Starting SimulateFromSeed with randomness created with seed %d", int(seed))
keys, addrs := mock.GeneratePrivKeyAddressPairs(numKeys)
r := rand.New(rand.NewSource(seed))
2018-07-17 15:04:10 -07:00
app.InitChain(abci.RequestInitChain{AppStateBytes: appStateFn(r, addrs)})
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-17 15:04:10 -07:00
// AssertAllInvariants asserts a list of provided invariants against application state
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)
}
}