github.com/pubgo/xprocess@v0.1.11/process_test.go (about)

     1  package xprocess_test
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"testing"
     7  	"time"
     8  
     9  	"github.com/pubgo/xerror"
    10  	"github.com/pubgo/xprocess"
    11  	"github.com/pubgo/xprocess/xprocess_group"
    12  	"github.com/stretchr/testify/assert"
    13  )
    14  
    15  func TestCancel(t *testing.T) {
    16  	cancel := xprocess.Go(func(ctx context.Context) {
    17  		for {
    18  			select {
    19  			case <-ctx.Done():
    20  				return
    21  			default:
    22  				time.Sleep(time.Millisecond * 100)
    23  				fmt.Println("g1")
    24  			}
    25  		}
    26  	})
    27  
    28  	time.Sleep(time.Second)
    29  	cancel()
    30  	time.Sleep(time.Second)
    31  }
    32  
    33  func TestName(t *testing.T) {
    34  	for {
    35  		xprocess.Go(func(ctx context.Context) {
    36  			time.Sleep(time.Second)
    37  			fmt.Println("g2")
    38  			return
    39  		})
    40  
    41  		xprocess.GoLoop(func(ctx context.Context) {
    42  			time.Sleep(time.Second)
    43  			fmt.Println("g3")
    44  		})
    45  
    46  		g := xprocess_group.New()
    47  		g.Go(func(ctx context.Context) {
    48  			fmt.Println("g4")
    49  		})
    50  
    51  		g.Go(func(ctx context.Context) {
    52  			fmt.Println("g5")
    53  		})
    54  
    55  		g.Go(func(ctx context.Context) {
    56  			fmt.Println("g6")
    57  			xerror.Panic(xerror.Fmt("test error"))
    58  		})
    59  
    60  		g.Wait()
    61  
    62  		g.Cancel()
    63  
    64  		time.Sleep(time.Second)
    65  	}
    66  }
    67  
    68  func TestTimeout(t *testing.T) {
    69  	err := xprocess.Timeout(time.Second, func(ctx context.Context) {
    70  		time.Sleep(time.Millisecond * 990)
    71  	})
    72  	assert.Nil(t, err)
    73  
    74  	err = xprocess.Timeout(time.Second, func(ctx context.Context) {
    75  		time.Sleep(time.Second + time.Millisecond*10)
    76  	})
    77  	assert.NotNil(t, err)
    78  }