github.com/hata/goseq@v0.0.0-20150316021154-a5ca66a92399/executor_test.go (about) 1 package goseq 2 3 import ( 4 "errors" 5 "fmt" 6 "testing" 7 "time" 8 ) 9 10 func TestNewExecutor(t *testing.T) { 11 ex := newExecutor(4) 12 defer ex.Stop() 13 if ex.max != 4 { 14 t.Error("NewExecutor should initialize max value.") 15 } 16 if len(ex.jobs) != 4 { 17 t.Error("NewExecutor should initialize jobs table.") 18 } 19 if len(ex.resultChannels) != 4 { 20 t.Error("NewExecutor should initialize resultChannels table.") 21 } 22 if ex.jobIndexChannel == nil { 23 t.Error("NewExecutor should initialize jobIndexChannel.") 24 } 25 if ex.freeJobIndexChannel == nil { 26 t.Error("NewExecutor should initialize freeJobIndexChannel.") 27 } 28 if len(ex.freeJobIndexChannel) != 4 { 29 t.Error("NewExecutor should have free list.") 30 } 31 } 32 33 func TestMax(t *testing.T) { 34 ex := newExecutor(4) 35 defer ex.Stop() 36 if ex.Max() != 4 { 37 t.Error("Executor.Max should return a max value.") 38 } 39 } 40 41 func TestExecute(t *testing.T) { 42 ex := newExecutor(4) 43 defer ex.Stop() 44 f := ex.Execute(func() (Any, error) { 45 time.Sleep(10) 46 return "finished", nil 47 }) 48 res, err := f.Result() 49 resText, ok := res.(string) 50 if !ok || resText != "finished" || err != nil { 51 t.Error("Execute should provide a future instance.") 52 } 53 res, err = f.Result() 54 resText, ok = res.(string) 55 if !ok || resText != "finished" || err != nil { 56 t.Error("Future should return the same contents again.") 57 } 58 } 59 60 func createJobFunc(i int, errText string) Job { 61 return func() (Any, error) { 62 time.Sleep(10) 63 return fmt.Sprintf("finished%d", i), errors.New(errText) 64 } 65 } 66 67 func TestRunFuture(t *testing.T) { 68 ex := newExecutor(2) 69 defer ex.Stop() 70 71 f1 := ex.Execute(createJobFunc(1, "")) 72 f2 := ex.Execute(createJobFunc(2, "")) 73 74 result1, _ := f1.Result() 75 result2, _ := f2.Result() 76 77 if result1.(string) != "finished1" || result2.(string) != "finished2" { 78 t.Error("Get finished.") 79 } 80 } 81 82 func TestAddSomeJobs(t *testing.T) { 83 ex := newExecutor(2) 84 defer ex.Stop() 85 results := make([]Future, 5) 86 for i := 0; i < 5; i++ { 87 results[i] = ex.Execute(createJobFunc(i, fmt.Sprintf("error%d", i))) 88 } 89 for i := 0; i < 5; i++ { 90 expected := fmt.Sprintf("finished%d", i) 91 expectedError := fmt.Sprintf("error%d", i) 92 res, err := results[i].Result() 93 resText := res.(string) 94 errText := err.Error() 95 if resText != expected || errText != expectedError { 96 t.Error("Finished value is incorrect.") 97 } 98 } 99 } 100 101 func TestNewFuture(t *testing.T) { 102 f := newFuture() 103 if f.finished { 104 t.Error("future.finished should be false.") 105 } 106 if f.waitChannel == nil { 107 t.Error("future.waitChannel should be initialized.") 108 } 109 }