github.com/go-board/x-go@v0.1.2-0.20220610024734-db1323f6cb15/concurrent/concurrent_test.go (about)

     1  package concurrent_test
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/stretchr/testify/require"
    10  
    11  	"github.com/go-board/x-go/concurrent"
    12  )
    13  
    14  func TestConcurrent(t *testing.T) {
    15  	t.Run("wait success", func(t *testing.T) {
    16  		now := time.Now()
    17  		c, _ := concurrent.NewConcurrent(context.Background())
    18  		c.Spawn(func() error {
    19  			time.Sleep(time.Second)
    20  			return nil
    21  		})
    22  		c.Spawn(func() error {
    23  			time.Sleep(time.Second * 2)
    24  			return nil
    25  		})
    26  		err := c.Wait(context.Background())
    27  		require.Nil(t, err, "errCh must be nil")
    28  		require.Equal(t, 2, int(time.Since(now).Seconds()), "longest elapsed time is two seconds")
    29  	})
    30  	t.Run("wait error", func(t *testing.T) {
    31  		now := time.Now()
    32  		c, _ := concurrent.NewConcurrent(context.Background())
    33  		c.Spawn(func() error {
    34  			time.Sleep(time.Second)
    35  			return nil
    36  		})
    37  		c.Spawn(func() error {
    38  			time.Sleep(time.Second * 2)
    39  			return errors.New("not found")
    40  		})
    41  		c.Spawn(func() error {
    42  			time.Sleep(time.Second * 3)
    43  			return nil
    44  		})
    45  		err := c.Wait(context.Background())
    46  		require.EqualError(t, err, "not found", "errCh must be not found")
    47  		require.Equal(t, 3, int(time.Since(now).Seconds()), "longest elapsed time is two seconds")
    48  	})
    49  	t.Run("wait error last", func(t *testing.T) {
    50  		now := time.Now()
    51  		c, _ := concurrent.NewConcurrent(context.Background())
    52  		var a int
    53  		c.Spawn(func() error {
    54  			a = 123
    55  			time.Sleep(time.Second)
    56  			return nil
    57  		})
    58  		c.Spawn(func() error {
    59  			time.Sleep(time.Second * 2)
    60  			return nil
    61  		})
    62  		c.Spawn(func() error {
    63  			time.Sleep(time.Second * 3)
    64  			return errors.New("timeout")
    65  		})
    66  		err := c.Wait(context.Background())
    67  		t.Logf("%+v\n", a)
    68  		require.EqualError(t, err, "timeout", "errCh must be timeout")
    69  		require.Equal(t, 3, int(time.Since(now).Seconds()), "longest elapsed time is two seconds")
    70  	})
    71  }