github.com/songzhibin97/go-baseutils@v0.0.2-0.20240302024150-487d8ce9c082/app/bconcurrent/fan_out_test.go (about)

     1  package bconcurrent
     2  
     3  import (
     4  	"sort"
     5  	"sync"
     6  	"testing"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  )
    10  
    11  func production() <-chan int {
    12  	out := make(chan int)
    13  	go func() {
    14  		defer close(out)
    15  		for i := 0; i < 10; i++ {
    16  			out <- i
    17  		}
    18  	}()
    19  	return out
    20  }
    21  
    22  func consumer(ch <-chan int) (ret []int) {
    23  	for v := range ch {
    24  		ret = append(ret, v)
    25  	}
    26  	sort.Slice(ret, func(i, j int) bool {
    27  		return ret[i] < ret[j]
    28  	})
    29  	return ret
    30  }
    31  
    32  func TestFanOut(t *testing.T) {
    33  	var outList []chan int
    34  	for i := 0; i < 10; i++ {
    35  		outList = append(outList, make(chan int))
    36  	}
    37  	FanOut[int](production(), outList, true)
    38  	wg := sync.WaitGroup{}
    39  	for _, c := range outList {
    40  		wg.Add(1)
    41  		go func(c chan int) {
    42  			defer wg.Done()
    43  			assert.Equal(t, consumer(c), []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9})
    44  		}(c)
    45  	}
    46  	wg.Wait()
    47  }