github.com/dfklegend/cell2/utils@v0.0.0-20240402033734-a0a9f3d9335d/waterfall/waterfall_sche_test.go (about)

     1  package waterfall
     2  
     3  import (
     4  	"fmt"
     5  	"testing"
     6  	"time"
     7  
     8  	"github.com/stretchr/testify/assert"
     9  
    10  	"github.com/dfklegend/cell2/utils/common"
    11  	scheP "github.com/dfklegend/cell2/utils/sche"
    12  )
    13  
    14  func Test_Sche_Simple(t *testing.T) {
    15  	sche := scheP.NewSche()
    16  
    17  	result := 0
    18  	Sche(sche, []Task{
    19  		func(callback Callback, args ...interface{}) {
    20  			callback(false, 1)
    21  		},
    22  		func(callback Callback, args ...interface{}) {
    23  			arg1 := args[0].(int)
    24  			callback(false, arg1+2)
    25  		},
    26  	}, func(err bool, args ...interface{}) {
    27  		result = args[0].(int)
    28  	})
    29  
    30  	go sche.Handler()
    31  	time.Sleep(time.Second * 1)
    32  	sche.Stop()
    33  
    34  	assert.Equal(t, 3, result)
    35  }
    36  
    37  func Test_Sche_SimpleBuilder(t *testing.T) {
    38  	sche := scheP.NewSche()
    39  
    40  	result := 0
    41  	NewBuilder(sche).Next(func(callback Callback, args ...interface{}) {
    42  		callback(false, 1)
    43  	}).Next(func(callback Callback, args ...interface{}) {
    44  		arg1 := args[0].(int)
    45  		callback(false, arg1+2)
    46  	}).Final(func(err bool, args ...interface{}) {
    47  		result = args[0].(int)
    48  	}).Do()
    49  
    50  	go sche.Handler()
    51  	time.Sleep(time.Second * 1)
    52  	sche.Stop()
    53  
    54  	assert.Equal(t, 3, result)
    55  }
    56  
    57  func Test_Sche_Panic(t *testing.T) {
    58  	sche := scheP.NewSche()
    59  
    60  	result := 0
    61  	Sche(sche, []Task{
    62  		func(callback Callback, args ...interface{}) {
    63  			callback(false, "hello")
    64  		},
    65  		func(callback Callback, args ...interface{}) {
    66  			// will panic
    67  			arg1 := args[0].(int)
    68  			callback(false, arg1+2)
    69  		},
    70  	}, func(err bool, args ...interface{}) {
    71  		result = -1
    72  	})
    73  
    74  	go sche.Handler()
    75  	time.Sleep(time.Second * 1)
    76  	sche.Stop()
    77  
    78  	assert.Equal(t, 0, result)
    79  }
    80  
    81  func Test_ExecInOneRoutine(t *testing.T) {
    82  	fmt.Println("---- Test_InOneRoutine ----")
    83  
    84  	testEnv.Reset()
    85  	sche := scheP.NewSche()
    86  	fn := func(tasks []Task, final FinalCallback) {
    87  		Sche(sche, tasks, final)
    88  	}
    89  	go testDo(fn)
    90  
    91  	go func() {
    92  		fmt.Println("taskInRoutine:", common.GetRoutineID())
    93  		sche.Handler()
    94  	}()
    95  	time.Sleep(time.Second * 3)
    96  	sche.Stop()
    97  
    98  	assert.Equal(t, true, testEnv.inSameRoutine)
    99  	fmt.Println("all over")
   100  }