github.com/anth0d/nomad@v0.0.0-20221214183521-ae3a0a2cad06/helper/broker/notify_test.go (about)

     1  package broker
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/hashicorp/nomad/ci"
     9  	"github.com/stretchr/testify/require"
    10  )
    11  
    12  func TestGenericNotifier(t *testing.T) {
    13  	ci.Parallel(t)
    14  
    15  	// Create the new notifier.
    16  	stopChan := make(chan struct{})
    17  	defer close(stopChan)
    18  
    19  	notifier := NewGenericNotifier()
    20  	go notifier.Run(stopChan)
    21  
    22  	// Ensure we have buffered channels.
    23  	require.Equal(t, 1, cap(notifier.publishCh))
    24  	require.Equal(t, 1, cap(notifier.subscribeCh))
    25  	require.Equal(t, 1, cap(notifier.unsubscribeCh))
    26  
    27  	// Test that the timeout works.
    28  	var timeoutWG sync.WaitGroup
    29  
    30  	for i := 0; i < 6; i++ {
    31  		go func(wg *sync.WaitGroup) {
    32  			wg.Add(1)
    33  			msg := notifier.WaitForChange(100 * time.Millisecond)
    34  			require.Equal(t, "wait timed out after 100ms", msg)
    35  			wg.Done()
    36  		}(&timeoutWG)
    37  	}
    38  	timeoutWG.Wait()
    39  
    40  	// Test that all subscribers recieve an update when a single notification
    41  	// is sent.
    42  	var notifiedWG sync.WaitGroup
    43  
    44  	for i := 0; i < 6; i++ {
    45  		go func(wg *sync.WaitGroup) {
    46  			wg.Add(1)
    47  			msg := notifier.WaitForChange(3 * time.Second)
    48  			require.Equal(t, "we got an update and not a timeout", msg)
    49  			wg.Done()
    50  		}(&notifiedWG)
    51  	}
    52  
    53  	notifier.Notify("we got an update and not a timeout")
    54  	notifiedWG.Wait()
    55  }