github.com/wangyougui/gf/v2@v2.6.5/util/gutil/gutil_z_unit_goroutine_test.go (about) 1 // Copyright GoFrame Author(https://goframe.org). All Rights Reserved. 2 // 3 // This Source Code Form is subject to the terms of the MIT License. 4 // If a copy of the MIT was not distributed with this file, 5 // You can obtain one at https://github.com/wangyougui/gf. 6 7 package gutil_test 8 9 import ( 10 "context" 11 "sync" 12 "testing" 13 14 "github.com/wangyougui/gf/v2/container/garray" 15 "github.com/wangyougui/gf/v2/test/gtest" 16 "github.com/wangyougui/gf/v2/util/gutil" 17 ) 18 19 func Test_Go(t *testing.T) { 20 gtest.C(t, func(t *gtest.T) { 21 var ( 22 wg = sync.WaitGroup{} 23 array = garray.NewArray(true) 24 ) 25 wg.Add(1) 26 gutil.Go(ctx, func(ctx context.Context) { 27 defer wg.Done() 28 array.Append(1) 29 }, nil) 30 wg.Wait() 31 t.Assert(array.Len(), 1) 32 }) 33 // recover 34 gtest.C(t, func(t *gtest.T) { 35 var ( 36 wg = sync.WaitGroup{} 37 array = garray.NewArray(true) 38 ) 39 wg.Add(1) 40 gutil.Go(ctx, func(ctx context.Context) { 41 defer wg.Done() 42 panic("error") 43 array.Append(1) 44 }, nil) 45 wg.Wait() 46 t.Assert(array.Len(), 0) 47 }) 48 gtest.C(t, func(t *gtest.T) { 49 var ( 50 wg = sync.WaitGroup{} 51 array = garray.NewArray(true) 52 ) 53 wg.Add(1) 54 gutil.Go(ctx, func(ctx context.Context) { 55 panic("error") 56 }, func(ctx context.Context, exception error) { 57 defer wg.Done() 58 array.Append(exception) 59 }) 60 wg.Wait() 61 t.Assert(array.Len(), 1) 62 t.Assert(array.At(0), "error") 63 }) 64 }