github.com/clubpay/ronykit/kit@v0.14.4-0.20240515065620-d0dace45cbc7/utils/singleflight_test.go (about)

     1  package utils_test
     2  
     3  import (
     4  	"sync"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/clubpay/ronykit/kit/utils"
     9  )
    10  
    11  func TestSingleFlight(t *testing.T) {
    12  	cnt := 0
    13  	fn := func() (string, error) {
    14  		cnt++
    15  		time.Sleep(time.Millisecond * 500)
    16  
    17  		return "hello", nil
    18  	}
    19  
    20  	sf := utils.SingleFlight[string]()
    21  
    22  	wg := sync.WaitGroup{}
    23  	for j := 0; j < 10; j++ {
    24  		for i := 0; i < 3; i++ {
    25  			wg.Add(1)
    26  			go func() {
    27  				defer wg.Done()
    28  
    29  				res, err := sf(fn)
    30  				if err != nil {
    31  					t.Error(err)
    32  				}
    33  				t.Log(res)
    34  			}()
    35  		}
    36  		wg.Wait()
    37  
    38  		if cnt != 1 {
    39  			t.Errorf("expected 10, got %d", cnt)
    40  		}
    41  
    42  		cnt = 0
    43  	}
    44  }