github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/consensus/dbft/core/roundchange_test.go (about)

     1  package core
     2  
     3  import (
     4  	"math/big"
     5  	"testing"
     6  
     7  	"github.com/quickchainproject/quickchain/common"
     8  	"github.com/quickchainproject/quickchain/consensus/dbft"
     9  	"github.com/quickchainproject/quickchain/consensus/dbft/validator"
    10  )
    11  
    12  func TestRoundChangeSet(t *testing.T) {
    13  	vset := validator.NewSet(generateValidators(4), bft.RoundRobin)
    14  	rc := newRoundChangeSet(vset)
    15  
    16  	view := &bft.View{
    17  		Sequence: big.NewInt(1),
    18  		Round:    big.NewInt(1),
    19  	}
    20  	r := &bft.Subject{
    21  		View:   view,
    22  		Digest: common.Hash{},
    23  	}
    24  	m, _ := Encode(r)
    25  
    26  	// Test Add()
    27  	// Add message from all validators
    28  	for i, v := range vset.List() {
    29  		msg := &message{
    30  			Code:    msgRoundChange,
    31  			Msg:     m,
    32  			Address: v.Address(),
    33  		}
    34  		rc.Add(view.Round, msg)
    35  		if rc.roundChanges[view.Round.Uint64()].Size() != i+1 {
    36  			t.Errorf("the size of round change messages mismatch: have %v, want %v", rc.roundChanges[view.Round.Uint64()].Size(), i+1)
    37  		}
    38  	}
    39  
    40  	// Add message again from all validators, but the size should be the same
    41  	for _, v := range vset.List() {
    42  		msg := &message{
    43  			Code:    msgRoundChange,
    44  			Msg:     m,
    45  			Address: v.Address(),
    46  		}
    47  		rc.Add(view.Round, msg)
    48  		if rc.roundChanges[view.Round.Uint64()].Size() != vset.Size() {
    49  			t.Errorf("the size of round change messages mismatch: have %v, want %v", rc.roundChanges[view.Round.Uint64()].Size(), vset.Size())
    50  		}
    51  	}
    52  
    53  	// Test MaxRound()
    54  	for i := 0; i < 10; i++ {
    55  		maxRound := rc.MaxRound(i)
    56  		if i <= vset.Size() {
    57  			if maxRound == nil || maxRound.Cmp(view.Round) != 0 {
    58  				t.Errorf("max round mismatch: have %v, want %v", maxRound, view.Round)
    59  			}
    60  		} else if maxRound != nil {
    61  			t.Errorf("max round mismatch: have %v, want nil", maxRound)
    62  		}
    63  	}
    64  
    65  	// Test Clear()
    66  	for i := int64(0); i < 2; i++ {
    67  		rc.Clear(big.NewInt(i))
    68  		if rc.roundChanges[view.Round.Uint64()].Size() != vset.Size() {
    69  			t.Errorf("the size of round change messages mismatch: have %v, want %v", rc.roundChanges[view.Round.Uint64()].Size(), vset.Size())
    70  		}
    71  	}
    72  	rc.Clear(big.NewInt(2))
    73  	if rc.roundChanges[view.Round.Uint64()] != nil {
    74  		t.Errorf("the change messages mismatch: have %v, want nil", rc.roundChanges[view.Round.Uint64()])
    75  	}
    76  }