github.com/arieschain/arieschain@v0.0.0-20191023063405-37c074544356/consensus/bft/backend/handler_test.go (about)

     1  package backend
     2  
     3  import (
     4  	"testing"
     5  
     6  	lru "github.com/hashicorp/golang-lru"
     7  	"github.com/quickchainproject/quickchain/common"
     8  	"github.com/quickchainproject/quickchain/consensus/bft"
     9  	"github.com/quickchainproject/quickchain/p2p"
    10  	"github.com/quickchainproject/quickchain/rlp"
    11  )
    12  
    13  func TestBFTMessage(t *testing.T) {
    14  	_, backend := newBlockChain(1)
    15  
    16  	// generate one msg
    17  	data := []byte("data1")
    18  	hash := bft.RLPHash(data)
    19  	msg := makeMsg(bftMsg, data)
    20  	addr := common.StringToAddress("address")
    21  
    22  	// 1. this message should not be in cache
    23  	// for peers
    24  	if _, ok := backend.recentMessages.Get(addr); ok {
    25  		t.Fatalf("the cache of messages for this peer should be nil")
    26  	}
    27  
    28  	// for self
    29  	if _, ok := backend.knownMessages.Get(hash); ok {
    30  		t.Fatalf("the cache of messages should be nil")
    31  	}
    32  
    33  	// 2. this message should be in cache after we handle it
    34  	_, err := backend.HandleMsg(addr, msg)
    35  	if err != nil {
    36  		t.Fatalf("handle message failed: %v", err)
    37  	}
    38  	// for peers
    39  	if ms, ok := backend.recentMessages.Get(addr); ms == nil || !ok {
    40  		t.Fatalf("the cache of messages for this peer cannot be nil")
    41  	} else if m, ok := ms.(*lru.ARCCache); !ok {
    42  		t.Fatalf("the cache of messages for this peer cannot be casted")
    43  	} else if _, ok := m.Get(hash); !ok {
    44  		t.Fatalf("the cache of messages for this peer cannot be found")
    45  	}
    46  
    47  	// for self
    48  	if _, ok := backend.knownMessages.Get(hash); !ok {
    49  		t.Fatalf("the cache of messages cannot be found")
    50  	}
    51  }
    52  
    53  func makeMsg(msgcode uint64, data interface{}) p2p.Msg {
    54  	size, r, _ := rlp.EncodeToReader(data)
    55  	return p2p.Msg{Code: msgcode, Size: uint32(size), Payload: r}
    56  }