github.com/bytom/bytom@v1.1.2-0.20221014091027-bbcba3df6075/netsync/chainmgr/block_process_test.go (about)

     1  package chainmgr
     2  
     3  import (
     4  	"io/ioutil"
     5  	"os"
     6  	"sync"
     7  	"testing"
     8  	"time"
     9  
    10  	dbm "github.com/bytom/bytom/database/leveldb"
    11  	"github.com/bytom/bytom/netsync/peers"
    12  	"github.com/bytom/bytom/protocol/bc/types"
    13  	"github.com/bytom/bytom/test/mock"
    14  	"github.com/bytom/bytom/testcontrol"
    15  )
    16  
    17  func TestBlockProcess(t *testing.T) {
    18  	if testcontrol.IgnoreTestTemporary {
    19  		return
    20  	}
    21  
    22  	tmp, err := ioutil.TempDir(".", "")
    23  	if err != nil {
    24  		t.Fatal(err)
    25  	}
    26  	defer os.RemoveAll(tmp)
    27  
    28  	testDB := dbm.NewDB("testdb", "leveldb", tmp)
    29  	defer testDB.Close()
    30  
    31  	cases := []struct {
    32  		blocks      []*types.Block
    33  		startHeight uint64
    34  		stopHeight  uint64
    35  	}{
    36  		{
    37  			blocks:      mockBlocks(nil, 200),
    38  			startHeight: 100,
    39  			stopHeight:  200,
    40  		},
    41  		{
    42  			blocks:      mockBlocks(nil, 200),
    43  			startHeight: 110,
    44  			stopHeight:  100,
    45  		},
    46  		{
    47  			blocks:      mockErrorBlocks(nil, 200, 150),
    48  			startHeight: 100,
    49  			stopHeight:  149,
    50  		},
    51  	}
    52  	s := newStorage(testDB)
    53  	mockChain := mock.NewChain()
    54  	for i, c := range cases {
    55  		for i := 0; i <= len(c.blocks)/2; i++ {
    56  			mockChain.SetBlockByHeight(uint64(i), c.blocks[i])
    57  			mockChain.SetBestBlockHeader(&c.blocks[i].BlockHeader)
    58  		}
    59  
    60  		if err := s.writeBlocks("testPeer", c.blocks); err != nil {
    61  			t.Fatal(err)
    62  		}
    63  
    64  		bp := newBlockProcessor(mockChain, s, peers.NewPeerSet(nil))
    65  		downloadNotifyCh := make(chan struct{}, 1)
    66  		ProcessStopCh := make(chan struct{})
    67  		var wg sync.WaitGroup
    68  		go func() {
    69  			time.Sleep(1 * time.Second)
    70  			close(downloadNotifyCh)
    71  		}()
    72  		wg.Add(1)
    73  
    74  		bp.process(downloadNotifyCh, ProcessStopCh, c.startHeight, &wg)
    75  		if bp.chain.BestBlockHeight() != c.stopHeight {
    76  			t.Fatalf("TestBlockProcess index: %d fail: got %d want %d", i, bp.chain.BestBlockHeight(), c.stopHeight)
    77  		}
    78  	}
    79  }