gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/lifecycle/group_test.go (about) 1 package lifecycle 2 3 import ( 4 "math/rand" 5 "testing" 6 "time" 7 ) 8 9 func TestGroup(t *testing.T) { 10 onStarting := func(lifecycle Lifecycle) { t.Logf("%s starting", lifecycle.Field("name")) } 11 onStarted := func(lifecycle Lifecycle, err error) { 12 if err != nil { 13 t.Logf("%s started with error(%s)", lifecycle.Field("name"), err.Error()) 14 } else { 15 t.Logf("%s started", lifecycle.Field("name")) 16 } 17 } 18 onClose := func(lifecycle Lifecycle, err error) { 19 if err != nil { 20 t.Logf("%s close with error(%s)", lifecycle.Field("name"), err.Error()) 21 } else { 22 t.Logf("%s close", lifecycle.Field("name")) 23 } 24 } 25 onClosed := func(lifecycle Lifecycle, err error) { 26 if err != nil { 27 t.Logf("%s exit with error(%s)", lifecycle.Field("name"), err.Error()) 28 } else { 29 t.Logf("%s exit", lifecycle.Field("name")) 30 } 31 } 32 starter := func(lifecycle Lifecycle, interrupter chan struct{}) (runFn InterruptedRunFunc, err error) { 33 select { 34 case <-time.After(time.Millisecond*time.Duration(rand.Intn(1000)) + time.Second): 35 case <-interrupter: 36 time.Sleep(time.Millisecond*time.Duration(rand.Intn(300)) + time.Millisecond*300) 37 return nil, NewInterruptedError("", "启动") 38 } 39 return func(Lifecycle, chan struct{}) error { 40 select { 41 case <-time.After(time.Millisecond*time.Duration(rand.Intn(5000)) + time.Second*5): 42 case <-interrupter: 43 time.Sleep(time.Millisecond*time.Duration(rand.Intn(500)) + time.Millisecond*500) 44 return nil 45 } 46 return nil 47 }, nil 48 } 49 g := NewGroup(). 50 MustAdd("test1", NewWithInterruptedStart(starter).OnStarting(onStarting).OnStarted(onStarted).OnClose(onClose).OnClosed(onClosed).SetField("name", "test1")).SetCloseAllOnExit(false).Group(). 51 MustAdd("test2", NewWithInterruptedStart(starter).OnStarting(onStarting).OnStarted(onStarted).OnClose(onClose).OnClosed(onClosed).SetField("name", "test2")).SetCloseAllOnExit(false).Group(). 52 MustAdd("test3", NewWithInterruptedStart(starter).OnStarting(onStarting).OnStarted(onStarted).OnClose(onClose).OnClosed(onClosed).SetField("name", "test3")).Group() 53 g.Run() 54 }