github.com/niubaoshu/goutils@v0.0.0-20180828035119-e8e576f66c2b/channel_test.go (about)

     1  package goutils_test
     2  
     3  import (
     4  	"testing"
     5  	"time"
     6  
     7  	"github.com/niubaoshu/goutils"
     8  )
     9  
    10  func TestChannel(t *testing.T) {
    11  	c := goutils.NewChannel(1, time.Second)
    12  	var a = 1
    13  	go c.Add(a)
    14  	select {
    15  	case <-c.FullChan:
    16  		is := c.Get()
    17  		for i := 0; i < len(is); i++ {
    18  			if is[i].(int) != 1 {
    19  				t.Fatalf("error %v", is[i].(int))
    20  			}
    21  		}
    22  	}
    23  }
    24  
    25  func TestChannelA(t *testing.T) {
    26  	c := goutils.NewChannel(10, time.Second)
    27  	loopNum := 10000000
    28  	exitch := make(chan struct{})
    29  	go func() {
    30  		for i := 0; i < loopNum; i++ {
    31  			c.Add(i)
    32  		}
    33  		exitch <- struct{}{}
    34  	}()
    35  
    36  	n := 0
    37  lb:
    38  	for {
    39  		select {
    40  		case <-c.FullChan:
    41  			r := c.Get()
    42  			for i := 0; i < len(r); i++ {
    43  				if r[i].(int) != n {
    44  					t.Error("error")
    45  				}
    46  				n++
    47  			}
    48  		case <-exitch:
    49  			if c.Len() != 0 {
    50  				go func() { exitch <- struct{}{} }()
    51  				break
    52  			}
    53  			if n != loopNum {
    54  				t.Error("error")
    55  			}
    56  			break lb
    57  		}
    58  	}
    59  }