github.com/hernad/nomad@v1.6.112/helper/broker/notify_test.go (about) 1 // Copyright (c) HashiCorp, Inc. 2 // SPDX-License-Identifier: MPL-2.0 3 4 package broker 5 6 import ( 7 "sync" 8 "testing" 9 "time" 10 11 "github.com/hernad/nomad/ci" 12 "github.com/stretchr/testify/require" 13 ) 14 15 func TestGenericNotifier(t *testing.T) { 16 ci.Parallel(t) 17 18 // Create the new notifier. 19 stopChan := make(chan struct{}) 20 defer close(stopChan) 21 22 notifier := NewGenericNotifier() 23 go notifier.Run(stopChan) 24 25 // Ensure we have buffered channels. 26 require.Equal(t, 1, cap(notifier.publishCh)) 27 require.Equal(t, 1, cap(notifier.subscribeCh)) 28 require.Equal(t, 1, cap(notifier.unsubscribeCh)) 29 30 // Test that the timeout works. 31 var timeoutWG sync.WaitGroup 32 33 for i := 0; i < 6; i++ { 34 go func(wg *sync.WaitGroup) { 35 wg.Add(1) 36 msg := notifier.WaitForChange(100 * time.Millisecond) 37 require.Equal(t, "wait timed out after 100ms", msg) 38 wg.Done() 39 }(&timeoutWG) 40 } 41 timeoutWG.Wait() 42 43 // Test that all subscribers receive an update when a single notification 44 // is sent. 45 var notifiedWG sync.WaitGroup 46 47 for i := 0; i < 6; i++ { 48 go func(wg *sync.WaitGroup) { 49 wg.Add(1) 50 msg := notifier.WaitForChange(3 * time.Second) 51 require.Equal(t, "we got an update and not a timeout", msg) 52 wg.Done() 53 }(¬ifiedWG) 54 } 55 56 // Ensure the routines have had time to start before sending the notify 57 // signal, otherwise the test is a flake. 58 time.Sleep(500 * time.Millisecond) 59 60 notifier.Notify("we got an update and not a timeout") 61 notifiedWG.Wait() 62 }