github.com/btcsuite/btcd@v0.24.0/blockchain/notifications_test.go (about)

     1  // Copyright (c) 2017 The btcsuite developers
     2  // Use of this source code is governed by an ISC
     3  // license that can be found in the LICENSE file.
     4  
     5  package blockchain
     6  
     7  import (
     8  	"testing"
     9  
    10  	"github.com/btcsuite/btcd/chaincfg"
    11  )
    12  
    13  // TestNotifications ensures that notification callbacks are fired on events.
    14  func TestNotifications(t *testing.T) {
    15  	blocks, err := loadBlocks("blk_0_to_4.dat.bz2")
    16  	if err != nil {
    17  		t.Fatalf("Error loading file: %v\n", err)
    18  	}
    19  
    20  	// Create a new database and chain instance to run tests against.
    21  	chain, teardownFunc, err := chainSetup("notifications",
    22  		&chaincfg.MainNetParams)
    23  	if err != nil {
    24  		t.Fatalf("Failed to setup chain instance: %v", err)
    25  	}
    26  	defer teardownFunc()
    27  
    28  	notificationCount := 0
    29  	callback := func(notification *Notification) {
    30  		if notification.Type == NTBlockAccepted {
    31  			notificationCount++
    32  		}
    33  	}
    34  
    35  	// Register callback multiple times then assert it is called that many
    36  	// times.
    37  	const numSubscribers = 3
    38  	for i := 0; i < numSubscribers; i++ {
    39  		chain.Subscribe(callback)
    40  	}
    41  
    42  	_, _, err = chain.ProcessBlock(blocks[1], BFNone)
    43  	if err != nil {
    44  		t.Fatalf("ProcessBlock fail on block 1: %v\n", err)
    45  	}
    46  
    47  	if notificationCount != numSubscribers {
    48  		t.Fatalf("Expected notification callback to be executed %d "+
    49  			"times, found %d", numSubscribers, notificationCount)
    50  	}
    51  }