github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zutil/chan_test.go (about)

     1  //go:build go1.18
     2  // +build go1.18
     3  
     4  package zutil_test
     5  
     6  import (
     7  	"testing"
     8  	"time"
     9  
    10  	"github.com/sohaha/zlsgo"
    11  	"github.com/sohaha/zlsgo/zsync"
    12  	"github.com/sohaha/zlsgo/zutil"
    13  )
    14  
    15  func TestNewChanUnbounded(t *testing.T) {
    16  	tt := zlsgo.NewTest(t)
    17  	ch := zutil.NewChan[any]()
    18  
    19  	var wg zsync.WaitGroup
    20  
    21  	for i := 0; i < 10; i++ {
    22  		i := i
    23  		wg.Go(func() {
    24  			ch.In() <- i
    25  		})
    26  	}
    27  
    28  	go func() {
    29  		_ = wg.Wait()
    30  		ch.Close()
    31  	}()
    32  
    33  	time.Sleep(time.Second / 4)
    34  	tt.EqualTrue(ch.Len() >= 10)
    35  
    36  	for v := range ch.Out() {
    37  		t.Log(v, ch.Len())
    38  	}
    39  }
    40  
    41  func TestNewChanUnbuffered(t *testing.T) {
    42  	tt := zlsgo.NewTest(t)
    43  	ch := zutil.NewChan[any](0)
    44  
    45  	var wg zsync.WaitGroup
    46  
    47  	for i := 0; i < 10; i++ {
    48  		i := i
    49  		wg.Go(func() {
    50  			ch.In() <- i
    51  		})
    52  	}
    53  
    54  	go func() {
    55  		_ = wg.Wait()
    56  		ch.Close()
    57  	}()
    58  
    59  	time.Sleep(time.Second / 4)
    60  	tt.Equal(0, ch.Len())
    61  
    62  	for v := range ch.Out() {
    63  		t.Log(v, ch.Len())
    64  	}
    65  }
    66  
    67  func TestNewChanBuffered(t *testing.T) {
    68  	tt := zlsgo.NewTest(t)
    69  	ch := zutil.NewChan[any](3)
    70  
    71  	var wg zsync.WaitGroup
    72  
    73  	for i := 0; i < 10; i++ {
    74  		i := i
    75  		wg.Go(func() {
    76  			ch.In() <- i
    77  		})
    78  	}
    79  
    80  	go func() {
    81  		_ = wg.Wait()
    82  		ch.Close()
    83  	}()
    84  
    85  	time.Sleep(time.Second / 4)
    86  	tt.EqualTrue(ch.Len() >= 3)
    87  
    88  	for v := range ch.Out() {
    89  		t.Log(v, ch.Len())
    90  	}
    91  }