github.com/artisanhe/tools@v1.0.1-0.20210607022958-19a8fef2eb04/runner/runner_test.go (about) 1 package runner 2 3 import ( 4 "context" 5 "fmt" 6 "sync/atomic" 7 "testing" 8 "time" 9 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func TestRunner(t *testing.T) { 14 tt := assert.New(t) 15 16 ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) 17 defer cancel() 18 19 wp := NewRunner(ctx, "normal", 3) 20 21 doneCount := int32(0) 22 23 for i := 0; i < int(9); i++ { 24 count := i 25 wp.Add(func(ctx context.Context) error { 26 time.Sleep(500 * time.Millisecond) 27 atomic.AddInt32(&doneCount, 1) 28 fmt.Printf("job done %d\n", count) 29 return nil 30 }, fmt.Sprintf("%d", count)) 31 } 32 33 if err := wp.Commit(); err != nil { 34 t.Logf("err %s", err.Error()) 35 } 36 37 tt.Equal(doneCount, int32(9)) 38 } 39 40 func TestRunnerWhenNoTask(t *testing.T) { 41 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) 42 defer cancel() 43 44 wp := NewRunner(ctx, "no task", 5) 45 46 err := wp.Commit() 47 t.Logf("err %v", err) 48 } 49 50 func TestRunnerWhenTimeout(t *testing.T) { 51 tt := assert.New(t) 52 53 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) 54 defer cancel() 55 56 wp := NewRunner(ctx, "timeout", 3) 57 58 for i := 0; i < int(9); i++ { 59 count := i 60 wp.Add(func(ctx context.Context) error { 61 fmt.Printf("job timeout %d\n", count) 62 time.Sleep(50 * time.Millisecond) 63 return nil 64 }, fmt.Sprintf("%d", i)) 65 } 66 67 err := wp.Commit() 68 tt.Error(err) 69 t.Log(err.Error()) 70 tt.True(IsErrTimeout(err)) 71 } 72 73 func TestRunnerWhenPanic(t *testing.T) { 74 tt := assert.New(t) 75 76 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) 77 defer cancel() 78 79 wp := NewRunner(ctx, "panic", 3) 80 81 for i := 0; i < int(9); i++ { 82 wp.Add(func(ctx context.Context) error { 83 panic("panic") 84 }, fmt.Sprintf("%d", i)) 85 } 86 87 err := wp.Commit() 88 tt.Error(err) 89 t.Log(err.Error()) 90 } 91 92 func TestRunnerWhenTaskSmallThankWorkers(t *testing.T) { 93 tt := assert.New(t) 94 95 ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond) 96 defer cancel() 97 98 wp := NewRunner(ctx, "panic", 3) 99 100 for i := 0; i < int(1); i++ { 101 wp.Add(func(ctx context.Context) error { 102 return nil 103 }, fmt.Sprintf("%d", i)) 104 } 105 106 err := wp.Commit() 107 tt.NoError(err) 108 }