github.com/google/fleetspeak@v0.1.15-0.20240426164851-4f31f62c1aea/fleetspeak/src/server/components/notifications/http_test.go (about)

     1  package notifications
     2  
     3  import (
     4  	"context"
     5  	"reflect"
     6  	"sync"
     7  	"testing"
     8  	"time"
     9  
    10  	log "github.com/golang/glog"
    11  
    12  	"github.com/google/fleetspeak/fleetspeak/src/common"
    13  	"github.com/google/fleetspeak/fleetspeak/src/server/notifications"
    14  )
    15  
    16  func TestListenNotify(t *testing.T) {
    17  	var l notifications.Listener
    18  	l = &HttpListener{
    19  		BindAddress: "localhost:",
    20  	}
    21  	c, err := l.Start()
    22  	if err != nil {
    23  		t.Fatalf("Failed to start listener: %v", err)
    24  	}
    25  	defer l.Stop()
    26  	log.Infof("Started [locahost:] listener, reports address: %v", l.Address())
    27  
    28  	mtx := &sync.Mutex{}
    29  	var gotIDs []common.ClientID
    30  	go func() {
    31  		for id := range c {
    32  			mtx.Lock()
    33  			gotIDs = append(gotIDs, id)
    34  			mtx.Unlock()
    35  		}
    36  	}()
    37  
    38  	n := HttpNotifier{}
    39  	id1, _ := common.StringToClientID("0000000000000001")
    40  	id2, _ := common.StringToClientID("0000000000000002")
    41  
    42  	for _, id := range []common.ClientID{id1, id2} {
    43  		if err := n.NewMessageForClient(context.Background(), l.Address(), id); err != nil {
    44  			t.Errorf("Unable to send notification for client: %v", err)
    45  		}
    46  	}
    47  
    48  	// TODO: Clean up concurrency in this test! We are not waiting for results correctly.
    49  	time.Sleep(500 * time.Millisecond)
    50  
    51  	mtx.Lock()
    52  	defer mtx.Unlock()
    53  	if !reflect.DeepEqual(gotIDs, []common.ClientID{id1, id2}) {
    54  		t.Errorf("Unexpected ids received got: %v want: %v", gotIDs, []common.ClientID{id1, id2})
    55  	}
    56  }