Browse Source

types: tests should not panic (#7506)

pull/7516/head
Sam Kleinman 2 years ago
committed by GitHub
parent
commit
752a3a6c24
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
10 changed files with 93 additions and 67 deletions
  1. +14
    -5
      types/block_test.go
  2. +3
    -1
      types/evidence_test.go
  3. +4
    -0
      types/light_test.go
  4. +15
    -15
      types/node_info_test.go
  5. +20
    -16
      types/proposal_test.go
  6. +4
    -0
      types/validation_test.go
  7. +19
    -24
      types/validator_set_test.go
  8. +4
    -5
      types/validator_test.go
  9. +9
    -1
      types/vote_set_test.go
  10. +1
    -0
      types/vote_test.go

+ 14
- 5
types/block_test.go View File

@ -68,6 +68,7 @@ func TestBlockValidateBasic(t *testing.T) {
voteSet, valSet, vals := randVoteSet(ctx, t, h-1, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev, err := NewMockDuplicateVoteEvidenceWithValidator(ctx, h, time.Now(), vals[0], "block-test-chain")
@ -154,6 +155,7 @@ func TestBlockMakePartSetWithEvidence(t *testing.T) {
voteSet, _, vals := randVoteSet(ctx, t, h-1, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
ev, err := NewMockDuplicateVoteEvidenceWithValidator(ctx, h, time.Now(), vals[0], "block-test-chain")
@ -175,6 +177,7 @@ func TestBlockHashesTo(t *testing.T) {
lastID := makeBlockIDRandom()
h := int64(3)
voteSet, valSet, vals := randVoteSet(ctx, t, h-1, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, h-1, 1, voteSet, vals, time.Now())
require.NoError(t, err)
@ -293,6 +296,7 @@ func TestCommitValidateBasic(t *testing.T) {
defer cancel()
com := randCommit(ctx, t, time.Now())
tc.malleateCommit(com)
assert.Equal(t, tc.expectErr, com.ValidateBasic() != nil, "Validate Basic had an unexpected result")
})
@ -365,7 +369,7 @@ func TestHeaderHash(t *testing.T) {
LastResultsHash: tmhash.Sum([]byte("last_results_hash")),
EvidenceHash: tmhash.Sum([]byte("evidence_hash")),
ProposerAddress: crypto.AddressHash([]byte("proposer_address")),
}, hexBytesFromString("F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")},
}, hexBytesFromString(t, "F740121F553B5418C3EFBD343C2DBFE9E007BB67B0D020A0741374BAB65242A4")},
{"nil header yields nil", nil, nil},
{"nil ValidatorsHash yields nil", &Header{
Version: version.Consensus{Block: 1, App: 2},
@ -475,16 +479,18 @@ func randCommit(ctx context.Context, t *testing.T, now time.Time) *Commit {
h := int64(3)
voteSet, _, vals := randVoteSet(ctx, t, h-1, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, h-1, 1, voteSet, vals, now)
require.NoError(t, err)
return commit
}
func hexBytesFromString(s string) bytes.HexBytes {
func hexBytesFromString(t *testing.T, s string) bytes.HexBytes {
t.Helper()
b, err := hex.DecodeString(s)
if err != nil {
panic(err)
}
require.NoError(t, err)
return bytes.HexBytes(b)
}
@ -558,6 +564,7 @@ func TestCommitToVoteSet(t *testing.T) {
voteSet, valSet, vals := randVoteSet(ctx, t, h-1, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, h-1, 1, voteSet, vals, time.Now())
assert.NoError(t, err)
chainID := voteSet.ChainID()
@ -684,6 +691,7 @@ func TestBlockProtoBuf(t *testing.T) {
h := mrand.Int63()
c1 := randCommit(ctx, t, time.Now())
b1 := MakeBlock(h, []Tx{Tx([]byte{1})}, &Commit{Signatures: []CommitSig{}}, []Evidence{})
b1.ProposerAddress = tmrand.Bytes(crypto.AddressSize)
@ -877,6 +885,7 @@ func TestSignedHeaderProtoBuf(t *testing.T) {
defer cancel()
commit := randCommit(ctx, t, time.Now())
h := MakeRandHeader()
sh := SignedHeader{Header: &h, Commit: commit}


+ 3
- 1
types/evidence_test.go View File

@ -112,6 +112,7 @@ func TestLightClientAttackEvidenceBasic(t *testing.T) {
commonHeight := height - 1
nValidators := 10
voteSet, valSet, privVals := randVoteSet(ctx, t, height, 1, tmproto.PrecommitType, nValidators, 1)
header := makeHeaderRandom()
header.Height = height
blockID := makeBlockID(tmhash.Sum([]byte("blockhash")), math.MaxInt32, tmhash.Sum([]byte("partshash")))
@ -174,6 +175,7 @@ func TestLightClientAttackEvidenceValidation(t *testing.T) {
commonHeight := height - 1
nValidators := 10
voteSet, valSet, privVals := randVoteSet(ctx, t, height, 1, tmproto.PrecommitType, nValidators, 1)
header := makeHeaderRandom()
header.Height = height
header.ValidatorsHash = valSet.Hash()
@ -358,7 +360,7 @@ func TestEvidenceVectors(t *testing.T) {
height := int64(5)
commonHeight := height - 1
nValidators := 10
voteSet, valSet, privVals := deterministicVoteSet(ctx, height, 1, tmproto.PrecommitType, 1)
voteSet, valSet, privVals := deterministicVoteSet(ctx, t, height, 1, tmproto.PrecommitType, 1)
header := &Header{
Version: version.Consensus{Block: 1, App: 1},
ChainID: chainID,


+ 4
- 0
types/light_test.go View File

@ -19,11 +19,13 @@ func TestLightBlockValidateBasic(t *testing.T) {
header := MakeRandHeader()
commit := randCommit(ctx, t, time.Now())
vals, _ := randValidatorPrivValSet(ctx, t, 5, 1)
header.Height = commit.Height
header.LastBlockID = commit.BlockID
header.ValidatorsHash = vals.Hash()
header.Version.Block = version.BlockProtocol
vals2, _ := randValidatorPrivValSet(ctx, t, 3, 1)
vals3 := vals.Copy()
vals3.Proposer = &Validator{}
commit.BlockID.Hash = header.Hash()
@ -66,6 +68,7 @@ func TestLightBlockProtobuf(t *testing.T) {
header := MakeRandHeader()
commit := randCommit(ctx, t, time.Now())
vals, _ := randValidatorPrivValSet(ctx, t, 5, 1)
header.Height = commit.Height
header.LastBlockID = commit.BlockID
header.Version.Block = version.BlockProtocol
@ -120,6 +123,7 @@ func TestSignedHeaderValidateBasic(t *testing.T) {
defer cancel()
commit := randCommit(ctx, t, time.Now())
chainID := "𠜎"
timestamp := time.Date(math.MaxInt64, 0, 0, 0, 0, 0, math.MaxInt64, time.UTC)
h := Header{


+ 15
- 15
types/node_info_test.go View File

@ -75,12 +75,12 @@ func TestNodeInfoValidate(t *testing.T) {
name := "testing"
// test case passes
ni = testNodeInfo(nodeKeyID, name)
ni = testNodeInfo(t, nodeKeyID, name)
ni.Channels = channels
assert.NoError(t, ni.Validate())
for _, tc := range testCases {
ni := testNodeInfo(nodeKeyID, name)
ni := testNodeInfo(t, nodeKeyID, name)
ni.Channels = channels
tc.malleateNodeInfo(&ni)
err := ni.Validate()
@ -97,11 +97,12 @@ func testNodeID() NodeID {
return NodeIDFromPubKey(ed25519.GenPrivKey().PubKey())
}
func testNodeInfo(id NodeID, name string) NodeInfo {
return testNodeInfoWithNetwork(id, name, "testing")
func testNodeInfo(t *testing.T, id NodeID, name string) NodeInfo {
return testNodeInfoWithNetwork(t, id, name, "testing")
}
func testNodeInfoWithNetwork(id NodeID, name, network string) NodeInfo {
func testNodeInfoWithNetwork(t *testing.T, id NodeID, name, network string) NodeInfo {
t.Helper()
return NodeInfo{
ProtocolVersion: ProtocolVersion{
P2P: version.P2PProtocol,
@ -109,23 +110,22 @@ func testNodeInfoWithNetwork(id NodeID, name, network string) NodeInfo {
App: 0,
},
NodeID: id,
ListenAddr: fmt.Sprintf("127.0.0.1:%d", getFreePort()),
ListenAddr: fmt.Sprintf("127.0.0.1:%d", getFreePort(t)),
Network: network,
Version: "1.2.3-rc0-deadbeef",
Channels: []byte{testCh},
Moniker: name,
Other: NodeInfoOther{
TxIndex: "on",
RPCAddress: fmt.Sprintf("127.0.0.1:%d", getFreePort()),
RPCAddress: fmt.Sprintf("127.0.0.1:%d", getFreePort(t)),
},
}
}
func getFreePort() int {
func getFreePort(t *testing.T) int {
t.Helper()
port, err := tmnet.GetFreePort()
if err != nil {
panic(err)
}
require.NoError(t, err)
return port
}
@ -137,8 +137,8 @@ func TestNodeInfoCompatible(t *testing.T) {
var newTestChannel byte = 0x2
// test NodeInfo is compatible
ni1 := testNodeInfo(nodeKey1ID, name)
ni2 := testNodeInfo(nodeKey2ID, name)
ni1 := testNodeInfo(t, nodeKey1ID, name)
ni2 := testNodeInfo(t, nodeKey2ID, name)
assert.NoError(t, ni1.CompatibleWith(ni2))
// add another channel; still compatible
@ -155,14 +155,14 @@ func TestNodeInfoCompatible(t *testing.T) {
}
for _, tc := range testCases {
ni := testNodeInfo(nodeKey2ID, name)
ni := testNodeInfo(t, nodeKey2ID, name)
tc.malleateNodeInfo(&ni)
assert.Error(t, ni1.CompatibleWith(ni))
}
}
func TestNodeInfoAddChannel(t *testing.T) {
nodeInfo := testNodeInfo(testNodeID(), "testing")
nodeInfo := testNodeInfo(t, testNodeID(), "testing")
nodeInfo.Channels = []byte{}
require.Empty(t, nodeInfo.Channels)


+ 20
- 16
types/proposal_test.go View File

@ -16,17 +16,13 @@ import (
tmproto "github.com/tendermint/tendermint/proto/tendermint/types"
)
var (
testProposal *Proposal
pbp *tmproto.Proposal
)
func getTestProposal(t testing.TB) *Proposal {
t.Helper()
func init() {
var stamp, err = time.Parse(TimeFormat, "2018-02-11T07:09:22.765Z")
if err != nil {
panic(err)
}
testProposal = &Proposal{
stamp, err := time.Parse(TimeFormat, "2018-02-11T07:09:22.765Z")
require.NoError(t, err)
return &Proposal{
Height: 12345,
Round: 23456,
BlockID: BlockID{Hash: []byte("--June_15_2020_amino_was_removed"),
@ -34,13 +30,12 @@ func init() {
POLRound: -1,
Timestamp: stamp,
}
pbp = testProposal.ToProto()
}
func TestProposalSignable(t *testing.T) {
chainID := "test_chain_id"
signBytes := ProposalSignBytes(chainID, pbp)
pb := CanonicalizeProposal(chainID, pbp)
signBytes := ProposalSignBytes(chainID, getTestProposal(t).ToProto())
pb := CanonicalizeProposal(chainID, getTestProposal(t).ToProto())
expected, err := protoio.MarshalDelimited(&pb)
require.NoError(t, err)
@ -48,7 +43,7 @@ func TestProposalSignable(t *testing.T) {
}
func TestProposalString(t *testing.T) {
str := testProposal.String()
str := getTestProposal(t).String()
expected := `Proposal{12345/23456 (2D2D4A756E655F31355F323032305F616D696E6F5F7761735F72656D6F766564:111:2D2D4A756E65, -1) 000000000000 @ 2018-02-11T07:09:22.765Z}`
if str != expected {
t.Errorf("got unexpected string for Proposal. Expected:\n%v\nGot:\n%v", expected, str)
@ -99,6 +94,10 @@ func TestProposalVerifySignature(t *testing.T) {
}
func BenchmarkProposalWriteSignBytes(b *testing.B) {
pbp := getTestProposal(b).ToProto()
b.ResetTimer()
for i := 0; i < b.N; i++ {
ProposalSignBytes("test_chain_id", pbp)
}
@ -109,7 +108,10 @@ func BenchmarkProposalSign(b *testing.B) {
defer cancel()
privVal := NewMockPV()
pbp := getTestProposal(b).ToProto()
b.ResetTimer()
for i := 0; i < b.N; i++ {
err := privVal.SignProposal(ctx, "test_chain_id", pbp)
if err != nil {
@ -119,17 +121,19 @@ func BenchmarkProposalSign(b *testing.B) {
}
func BenchmarkProposalVerifySignature(b *testing.B) {
testProposal := getTestProposal(b)
pbp := testProposal.ToProto()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
b.ResetTimer()
privVal := NewMockPV()
err := privVal.SignProposal(ctx, "test_chain_id", pbp)
require.NoError(b, err)
pubKey, err := privVal.GetPubKey(ctx)
require.NoError(b, err)
b.ResetTimer()
for i := 0; i < b.N; i++ {
pubKey.VerifySignature(ProposalSignBytes("test_chain_id", pbp), testProposal.Signature)
}


+ 4
- 0
types/validation_test.go View File

@ -64,6 +64,7 @@ func TestValidatorSet_VerifyCommit_All(t *testing.T) {
defer cancel()
_, valSet, vals := randVoteSet(ctx, t, tc.height, round, tmproto.PrecommitType, tc.valSize, 10)
totalVotes := tc.blockVotes + tc.absentVotes + tc.nilVotes
sigs := make([]CommitSig, totalVotes)
vi := 0
@ -146,6 +147,7 @@ func TestValidatorSet_VerifyCommit_CheckAllSignatures(t *testing.T) {
voteSet, valSet, vals := randVoteSet(ctx, t, h, 0, tmproto.PrecommitType, 4, 10)
commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
require.NoError(t, err)
require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit))
@ -175,6 +177,7 @@ func TestValidatorSet_VerifyCommitLight_ReturnsAsSoonAsMajorityOfVotingPowerSign
voteSet, valSet, vals := randVoteSet(ctx, t, h, 0, tmproto.PrecommitType, 4, 10)
commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
require.NoError(t, err)
require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit))
@ -201,6 +204,7 @@ func TestValidatorSet_VerifyCommitLightTrusting_ReturnsAsSoonAsTrustLevelOfVotin
voteSet, valSet, vals := randVoteSet(ctx, t, h, 0, tmproto.PrecommitType, 4, 10)
commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
require.NoError(t, err)
require.NoError(t, valSet.VerifyCommit(chainID, blockID, h, commit))


+ 19
- 24
types/validator_set_test.go View File

@ -86,6 +86,7 @@ func TestValidatorSetValidateBasic(t *testing.T) {
val, _, err := randValidator(ctx, false, 1)
require.NoError(t, err)
badVal := &Validator{}
testCases := []struct {
@ -178,9 +179,7 @@ func BenchmarkValidatorSetCopy(b *testing.B) {
pubKey := privKey.PubKey()
val := NewValidator(pubKey, 10)
err := vset.UpdateWithChangeSet([]*Validator{val})
if err != nil {
panic("Failed to add validator")
}
require.NoError(b, err)
}
b.StartTimer()
@ -337,8 +336,8 @@ func TestProposerSelection3(t *testing.T) {
}
// serialize, deserialize, check proposer
b := vset.toBytes()
vset = vset.fromBytes(b)
b := vset.toBytes(t)
vset = vset.fromBytes(t, b)
computed := vset.GetProposer() // findGetProposer()
if i != 0 {
@ -394,8 +393,9 @@ func randValidator(ctx context.Context, randPower bool, minPower int64) (*Valida
}
pubKey, err := privVal.GetPubKey(ctx)
if err != nil {
return nil, nil, fmt.Errorf("could not retrieve pubkey %w", err)
return nil, nil, err
}
val := NewValidator(pubKey, votePower)
return val, privVal, nil
}
@ -410,32 +410,23 @@ func randModuloValidatorSet(numValidators int) *ValidatorSet {
return NewValidatorSet(validators)
}
func (vals *ValidatorSet) toBytes() []byte {
func (vals *ValidatorSet) toBytes(t *testing.T) []byte {
pbvs, err := vals.ToProto()
if err != nil {
panic(err)
}
require.NoError(t, err)
bz, err := pbvs.Marshal()
if err != nil {
panic(err)
}
require.NoError(t, err)
return bz
}
func (vals *ValidatorSet) fromBytes(b []byte) *ValidatorSet {
func (vals *ValidatorSet) fromBytes(t *testing.T, b []byte) *ValidatorSet {
pbvs := new(tmproto.ValidatorSet)
err := pbvs.Unmarshal(b)
if err != nil {
// DATA HAS BEEN CORRUPTED OR THE SPEC HAS CHANGED
panic(err)
}
require.NoError(t, err)
vs, err := ValidatorSetFromProto(pbvs)
if err != nil {
panic(err)
}
require.NoError(t, err)
return vs
}
@ -1148,7 +1139,7 @@ type testVSetCfg struct {
func randTestVSetCfg(t *testing.T, nBase, nAddMax int) testVSetCfg {
if nBase <= 0 || nAddMax < 0 {
panic(fmt.Sprintf("bad parameters %v %v", nBase, nAddMax))
t.Fatalf("bad parameters %v %v", nBase, nAddMax)
}
const maxPower = 1000
@ -1427,6 +1418,7 @@ func TestValidatorSetProtoBuf(t *testing.T) {
valset3.Proposer = nil
valset4, _ := randValidatorPrivValSet(ctx, t, 10, 100)
valset4.Proposer = &Validator{}
testCases := []struct {
@ -1573,6 +1565,7 @@ func BenchmarkValidatorSet_VerifyCommitLight_Ed25519(b *testing.B) { // nolint
b.ReportAllocs()
// generate n validators
voteSet, valSet, vals := randVoteSet(ctx, b, h, 0, tmproto.PrecommitType, n, int64(n*5))
// create a commit with n validators
commit, err := makeCommit(ctx, blockID, h, 0, voteSet, vals, time.Now())
require.NoError(b, err)
@ -1618,15 +1611,17 @@ func BenchmarkValidatorSet_VerifyCommitLightTrusting_Ed25519(b *testing.B) {
// where each validator has a power of 50
//
// EXPOSED FOR TESTING.
func deterministicValidatorSet(ctx context.Context) (*ValidatorSet, []PrivValidator) {
func deterministicValidatorSet(ctx context.Context, t *testing.T) (*ValidatorSet, []PrivValidator) {
var (
valz = make([]*Validator, 10)
privValidators = make([]PrivValidator, 10)
)
t.Helper()
for i := 0; i < 10; i++ {
// val, privValidator := DeterministicValidator(ed25519.PrivKey([]byte(deterministicKeys[i])))
val, privValidator := deterministicValidator(ctx, ed25519.GenPrivKeyFromSecret([]byte(fmt.Sprintf("key: %x", i))))
val, privValidator := deterministicValidator(ctx, t, ed25519.GenPrivKeyFromSecret([]byte(fmt.Sprintf("key: %x", i))))
valz[i] = val
privValidators[i] = privValidator
}


+ 4
- 5
types/validator_test.go View File

@ -2,7 +2,6 @@ package types
import (
"context"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
@ -16,6 +15,7 @@ func TestValidatorProtoBuf(t *testing.T) {
val, _, err := randValidator(ctx, true, 100)
require.NoError(t, err)
testCases := []struct {
msg string
v1 *Validator
@ -112,14 +112,13 @@ func TestValidatorValidateBasic(t *testing.T) {
// deterministicValidator returns a deterministic validator, useful for testing.
// UNSTABLE
func deterministicValidator(ctx context.Context, key crypto.PrivKey) (*Validator, PrivValidator) {
func deterministicValidator(ctx context.Context, t *testing.T, key crypto.PrivKey) (*Validator, PrivValidator) {
t.Helper()
privVal := NewMockPV()
privVal.PrivKey = key
var votePower int64 = 50
pubKey, err := privVal.GetPubKey(ctx)
if err != nil {
panic(fmt.Errorf("could not retrieve pubkey %w", err))
}
require.NoError(t, err, "could not retrieve pubkey")
val := NewValidator(pubKey, votePower)
return val, privVal
}

+ 9
- 1
types/vote_set_test.go View File

@ -21,6 +21,7 @@ func TestVoteSet_AddVote_Good(t *testing.T) {
height, round := int64(1), int32(0)
voteSet, _, privValidators := randVoteSet(ctx, t, height, round, tmproto.PrevoteType, 10, 1)
val0 := privValidators[0]
val0p, err := val0.GetPubKey(ctx)
@ -289,6 +290,7 @@ func TestVoteSet_Conflicts(t *testing.T) {
height, round := int64(1), int32(0)
voteSet, _, privValidators := randVoteSet(ctx, t, height, round, tmproto.PrevoteType, 4, 1)
blockHash1 := tmrand.Bytes(32)
blockHash2 := tmrand.Bytes(32)
@ -421,6 +423,7 @@ func TestVoteSet_MakeCommit(t *testing.T) {
height, round := int64(1), int32(0)
voteSet, _, privValidators := randVoteSet(ctx, t, height, round, tmproto.PrecommitType, 10, 1)
blockHash, blockPartSetHeader := crypto.CRandBytes(32), PartSetHeader{123, crypto.CRandBytes(32)}
voteProto := &Vote{
@ -504,18 +507,22 @@ func randVoteSet(
numValidators int,
votingPower int64,
) (*VoteSet, *ValidatorSet, []PrivValidator) {
t.Helper()
valSet, privValidators := randValidatorPrivValSet(ctx, t, numValidators, votingPower)
return NewVoteSet("test_chain_id", height, round, signedMsgType, valSet), valSet, privValidators
}
func deterministicVoteSet(
ctx context.Context,
t *testing.T,
height int64,
round int32,
signedMsgType tmproto.SignedMsgType,
votingPower int64,
) (*VoteSet, *ValidatorSet, []PrivValidator) {
valSet, privValidators := deterministicValidatorSet(ctx)
t.Helper()
valSet, privValidators := deterministicValidatorSet(ctx, t)
return NewVoteSet("test_chain_id", height, round, signedMsgType, valSet), valSet, privValidators
}
@ -528,6 +535,7 @@ func randValidatorPrivValSet(ctx context.Context, t testing.TB, numValidators in
for i := 0; i < numValidators; i++ {
val, privValidator, err := randValidator(ctx, false, votingPower)
require.NoError(t, err)
valz[i] = val
privValidators[i] = privValidator
}


+ 1
- 0
types/vote_test.go View File

@ -315,6 +315,7 @@ func getSampleCommit(ctx context.Context, t testing.TB) *Commit {
lastID := makeBlockIDRandom()
voteSet, _, vals := randVoteSet(ctx, t, 2, 1, tmproto.PrecommitType, 10, 1)
commit, err := makeCommit(ctx, lastID, 2, 1, voteSet, vals, time.Now())
require.NoError(t, err)
return commit


Loading…
Cancel
Save