github.com/0xsequence/ethkit@v1.25.0/ethmonitor/pubsub_test.go (about)

     1  package ethmonitor
     2  
     3  import (
     4  	"math/big"
     5  	"strings"
     6  	"testing"
     7  
     8  	"github.com/0xsequence/ethkit/go-ethereum/common"
     9  	"github.com/0xsequence/ethkit/go-ethereum/core/types"
    10  	"github.com/stretchr/testify/require"
    11  )
    12  
    13  func TestQueueBasic(t *testing.T) {
    14  	qu := newQueue(100)
    15  
    16  	require.True(t, qu.len() == 0)
    17  
    18  	// blocks := mockBlockchain(5)
    19  	// for _, b := range blocks {
    20  	// 	fmt.Println("=>", b.NumberU64(), b.Hash().Hex(), b.ParentHash().Hex())
    21  	// }
    22  
    23  	events := Blocks{}
    24  	for i, b := range mockBlockchain(5) {
    25  		_ = i
    26  		events = append(events, &Block{
    27  			Block: b,
    28  			Event: Added,
    29  			OK:    i < 3, // first 3 are OK
    30  			// OK: true,
    31  		})
    32  	}
    33  
    34  	err := qu.enqueue(events)
    35  	require.NoError(t, err)
    36  	require.Len(t, qu.events, 5)
    37  
    38  	events2, ok := qu.dequeue(0)
    39  	require.True(t, ok)
    40  	require.NotEmpty(t, events2)
    41  	require.Len(t, events2, 3)
    42  
    43  	require.Equal(t, uint64(1), events[0].Block.NumberU64())
    44  	require.Equal(t, uint64(2), events[1].Block.NumberU64())
    45  	require.Equal(t, uint64(3), events[2].Block.NumberU64())
    46  }
    47  
    48  func TestQueueMore(t *testing.T) {
    49  	qu := newQueue(100)
    50  
    51  	require.True(t, qu.len() == 0)
    52  
    53  	blocks := mockBlockchain(10)
    54  
    55  	// TODO: we can add more tests to join/merge blocks as it relates
    56  	// to the `chain#sweep` method.
    57  
    58  	events := Blocks{
    59  		{Block: blocks[0], Event: Added, OK: true},
    60  	}
    61  
    62  	err := qu.enqueue(events)
    63  	require.NoError(t, err)
    64  	require.Len(t, qu.events, 1)
    65  
    66  	events2, ok := qu.dequeue(0)
    67  	require.True(t, ok)
    68  	require.NotEmpty(t, events2)
    69  	require.Len(t, events2, 1)
    70  
    71  	require.Equal(t, uint64(1), events[0].Block.NumberU64())
    72  }
    73  
    74  func mockBlockchain(size int) []*types.Block {
    75  	bc := []*types.Block{}
    76  	for i := 0; i < size; i++ {
    77  		var parentHash string
    78  		if i == 0 {
    79  			parentHash = "0x0"
    80  		} else {
    81  			parentHash = bc[i-1].Hash().Hex()
    82  		}
    83  		b := mockBlock(parentHash, i+1)
    84  		bc = append(bc, b)
    85  	}
    86  	return bc
    87  }
    88  
    89  func mockBlock(parentHash string, blockNum int) *types.Block {
    90  	if !strings.HasPrefix(parentHash, "0x") {
    91  		panic("parentHash needs 0x prefix")
    92  	}
    93  	return types.NewBlockWithHeader(&types.Header{
    94  		ParentHash: common.HexToHash(parentHash),
    95  		Number:     big.NewInt(int64(blockNum)),
    96  	})
    97  }