future_test.go (2146B)
1 package futures 2 3 import ( 4 "errors" 5 "testing" 6 "time" 7 ) 8 9 var ( 10 rejectedErr = errors.New("rejected") 11 ) 12 13 func action(v bool) (bool, error) { 14 return !v, nil 15 } 16 17 func heavyAction(v bool) *Future[bool] { 18 time.Sleep(100 * time.Millisecond) 19 return Resolve(!v) 20 } 21 22 func TestFuture(t *testing.T) { 23 tests := []struct { 24 name string 25 handler func() (int, error) 26 reject bool 27 }{ 28 { 29 "should be resolved", 30 func() (int, error) { 31 time.Sleep(100 * time.Millisecond) 32 return 42, nil 33 }, 34 false, 35 }, 36 { 37 "should be rejected", 38 func() (int, error) { 39 time.Sleep(100 * time.Millisecond) 40 return 0, errors.New("rejected") 41 }, 42 true, 43 }, 44 } 45 for _, tt := range tests { 46 t.Run(tt.name, func(t *testing.T) { 47 gotValue, err := Await(Run(tt.handler)) 48 if tt.reject { 49 if err == nil { 50 t.Errorf("should be rejected") 51 } 52 return 53 } 54 if gotValue != 42 { 55 t.Errorf("gotValue = %v, want 42", gotValue) 56 } 57 }) 58 } 59 } 60 61 func TestMap(t *testing.T) { 62 tests := []struct { 63 name string 64 f *Future[bool] 65 want *Future[bool] 66 }{ 67 { 68 "resolved then", 69 Resolve(false), 70 Resolve(true), 71 }, 72 { 73 "rejected then", 74 Reject[bool](rejectedErr), 75 Reject[bool](rejectedErr), 76 }, 77 } 78 for _, tt := range tests { 79 t.Run(tt.name, func(t *testing.T) { 80 f := Map(tt.f, action) 81 got, err := Await(f) 82 want, wantErr := Unwrap(tt.want) 83 if err != wantErr { 84 t.Errorf("err = %v, want %v", err, wantErr) 85 return 86 } 87 if got != want { 88 t.Errorf("got = %v, want %v", got, want) 89 } 90 }) 91 } 92 } 93 94 func TestFlatMap(t *testing.T) { 95 tests := []struct { 96 name string 97 f *Future[bool] 98 want *Future[bool] 99 }{ 100 { 101 "resolved then", 102 Resolve(false), 103 Resolve(true), 104 }, 105 { 106 "rejected then", 107 Reject[bool](rejectedErr), 108 Reject[bool](rejectedErr), 109 }, 110 } 111 for _, tt := range tests { 112 t.Run(tt.name, func(t *testing.T) { 113 f := FlatMap(tt.f, heavyAction) 114 got, err := Await(f) 115 want, wantErr := Unwrap(tt.want) 116 if err != wantErr { 117 t.Errorf("err = %v, want %v", err, wantErr) 118 return 119 } 120 if got != want { 121 t.Errorf("got = %v, want %v", got, want) 122 } 123 }) 124 } 125 }