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

     1  package bconcurrent
     2  
     3  import (
     4  	"sort"
     5  	"testing"
     6  
     7  	"github.com/stretchr/testify/assert"
     8  )
     9  
    10  func fanIn(start, end int) <-chan int {
    11  	out := make(chan int)
    12  	go func() {
    13  		defer close(out)
    14  		for i := start; i < end; i++ {
    15  			out <- i
    16  		}
    17  	}()
    18  	return out
    19  }
    20  
    21  func TestFanInRec(t *testing.T) {
    22  	out := FanInRec[int](fanIn(0, 6), fanIn(6, 11), fanIn(11, 20))
    23  	outSlice := make([]int, 0)
    24  	for v := range out {
    25  		outSlice = append(outSlice, v)
    26  	}
    27  	assert.Len(t, outSlice, 20)
    28  	sort.Slice(outSlice, func(i, j int) bool {
    29  		return outSlice[i] < outSlice[j]
    30  	})
    31  	assert.Equal(t, outSlice, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19})
    32  }
    33  
    34  func TestMergeChannel(t *testing.T) {
    35  	out := MergeChannel[int](fanIn(0, 6), fanIn(6, 11))
    36  	outSlice := make([]int, 0)
    37  	for v := range out {
    38  		outSlice = append(outSlice, v)
    39  	}
    40  	assert.Len(t, outSlice, 11)
    41  	sort.Slice(outSlice, func(i, j int) bool {
    42  		return outSlice[i] < outSlice[j]
    43  	})
    44  	assert.Equal(t, outSlice, []int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
    45  }