OSDN Git Service

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