github.com/mailru/activerecord@v1.12.2/pkg/iproto/syncutil/taskrunner_test.go (about) 1 package syncutil 2 3 import ( 4 "fmt" 5 "testing" 6 "time" 7 8 "golang.org/x/net/context" 9 ) 10 11 func TestTaskRunnerDo(t *testing.T) { 12 tr := TaskRunner{} 13 14 var rcvrs []<-chan error 15 16 taskRunTime := time.Duration(10 * time.Millisecond) 17 taskWaitTime := time.Duration(12 * time.Millisecond) 18 taskSubscribersNumber := 10 19 20 for i := 0; i < taskSubscribersNumber; i++ { 21 rcvrs = append(rcvrs, tr.Do(context.Background(), func(ctx context.Context) error { 22 time.Sleep(taskRunTime) 23 24 return fmt.Errorf("Some error") 25 })) 26 } 27 28 for _, rcvr := range rcvrs { 29 select { 30 case <-rcvr: 31 case <-time.After(taskWaitTime): 32 t.Fatal("must have already received task result for all receivers") 33 } 34 } 35 } 36 37 func TestTaskRunnerCancel(t *testing.T) { 38 tr := TaskRunner{} 39 40 result := tr.Do(context.Background(), func(ctx context.Context) error { 41 <-ctx.Done() 42 return nil 43 }) 44 45 time.Sleep(10 * time.Millisecond) 46 47 tr.Cancel() 48 49 select { 50 case <-result: 51 case <-time.After(10 * time.Millisecond): 52 t.Fatal("wanted task to be canceled") 53 } 54 } 55 56 func TestTaskRunnerRecovery(t *testing.T) { 57 tr := TaskRunner{} 58 59 var rcvrs []<-chan error 60 61 taskWaitTime := time.Duration(12 * time.Millisecond) 62 taskSubscribersNumber := 2 63 64 for i := 0; i < taskSubscribersNumber; i++ { 65 rcvrs = append(rcvrs, tr.Do(context.Background(), func(ctx context.Context) error { 66 panic("panic") 67 })) 68 } 69 70 for _, rcvr := range rcvrs { 71 select { 72 case response := <-rcvr: 73 if response != ErrTaskPanic { 74 t.Fatal("must have received task panic error for all receivers") 75 } 76 case <-time.After(taskWaitTime): 77 t.Fatal("must have already received task result for all receivers") 78 } 79 } 80 }