github.com/onflow/flow-go@v0.35.7-crescendo-preview.23-atree-inlining/module/events/finalized_header_cache_test.go (about)

     1  package events
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/onflow/flow-go/consensus/hotstuff/model"
    12  	"github.com/onflow/flow-go/model/flow"
    13  	"github.com/onflow/flow-go/module/irrecoverable"
    14  	protocolmock "github.com/onflow/flow-go/state/protocol/mock"
    15  	"github.com/onflow/flow-go/utils/unittest"
    16  )
    17  
    18  // TestFinalizedHeaderCache validates that the FinalizedHeaderCache can be constructed
    19  // with an initial value, and updated with events through the FinalizationActor.
    20  func TestFinalizedHeaderCache(t *testing.T) {
    21  	final := unittest.BlockHeaderFixture()
    22  
    23  	state := protocolmock.NewState(t)
    24  	snap := protocolmock.NewSnapshot(t)
    25  	state.On("Final").Return(snap)
    26  	snap.On("Head").Return(
    27  		func() *flow.Header { return final },
    28  		func() error { return nil })
    29  
    30  	cache, worker, err := NewFinalizedHeaderCache(state)
    31  	require.NoError(t, err)
    32  
    33  	// cache should be initialized
    34  	assert.Equal(t, final, cache.Get())
    35  
    36  	ctx, cancel := irrecoverable.NewMockSignalerContextWithCancel(t, context.Background())
    37  	defer cancel()
    38  	go worker(ctx, func() {})
    39  
    40  	// change the latest finalized block and mock a BlockFinalized event
    41  	final = unittest.BlockHeaderFixture(
    42  		unittest.HeaderWithView(final.View+1),
    43  		unittest.WithHeaderHeight(final.Height+1))
    44  	cache.OnFinalizedBlock(model.BlockFromFlow(final))
    45  
    46  	// the cache should be updated
    47  	assert.Eventually(t, func() bool {
    48  		return final.ID() == cache.Get().ID()
    49  	}, time.Second, time.Millisecond*10)
    50  }