github.com/git-amp/amp-sdk-go@v0.7.5/stdlib/utils/mailbox_test.go (about)

     1  package utils_test
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/stretchr/testify/require"
     8  
     9  	"github.com/git-amp/amp-sdk-go/stdlib/utils"
    10  )
    11  
    12  func TestMailbox(t *testing.T) {
    13  	t.Parallel()
    14  
    15  	m := utils.NewMailbox(10)
    16  
    17  	var (
    18  		expected  = []int{2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    19  		toDeliver = []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}
    20  		recvd     []int
    21  	)
    22  
    23  	for _, i := range toDeliver {
    24  		m.Deliver(i)
    25  	}
    26  
    27  	chDone := make(chan struct{})
    28  	go func() {
    29  		defer close(chDone)
    30  		for {
    31  			select {
    32  			case <-time.After(3 * time.Second):
    33  				return
    34  			case <-m.Notify():
    35  				for {
    36  					x := m.Retrieve()
    37  					if x == nil {
    38  						break
    39  					}
    40  					recvd = append(recvd, x.(int))
    41  				}
    42  			}
    43  		}
    44  	}()
    45  
    46  	<-chDone
    47  
    48  	if len(recvd) > 10 {
    49  		t.Fatal("received too many")
    50  	} else if len(recvd) < 10 {
    51  		t.Fatal("received too few")
    52  	}
    53  	require.Equal(t, expected, recvd)
    54  }