-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpromise_test.go
83 lines (65 loc) · 1.95 KB
/
promise_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
package result
import (
"context"
"fmt"
"sync"
"testing"
"time"
)
func TestPromiseWait(t *testing.T) {
type test struct {
promiseFunc func(ctx context.Context) (string, error)
ctx context.Context
waitCtx context.Context
expectedValue string
expectError bool
}
normalFunc := func(ctx context.Context) (string, error) {
return "normal", nil
}
errorFunc := func(ctx context.Context) (string, error) {
return "", fmt.Errorf("error")
}
ctxFunc := func(ctx context.Context) (string, error) {
select {
case <-ctx.Done():
return "", ctx.Err()
}
}
canceledContext, cancel := context.WithCancel(context.Background())
cancel()
neverFunc := func(ctx context.Context) (string, error) {
select {
case <-ctx.Done():
}
return "never", nil
}
timeoutContext, cancel := context.WithTimeout(context.Background(), 1*time.Second)
defer cancel()
tests := []test{
{promiseFunc: normalFunc, ctx: context.Background(), waitCtx: context.Background(), expectedValue: "normal", expectError: false},
{promiseFunc: errorFunc, ctx: context.Background(), waitCtx: context.Background(), expectedValue: "", expectError: true},
{promiseFunc: ctxFunc, ctx: canceledContext, waitCtx: context.Background(), expectedValue: "", expectError: true},
{promiseFunc: neverFunc, ctx: context.Background(), waitCtx: timeoutContext, expectedValue: "", expectError: true},
}
for _, tc := range tests {
p := NewPromise(tc.ctx, tc.promiseFunc)
wg := sync.WaitGroup{}
wg.Add(1)
var gotValue string
var gotError error
go func(p *Promise[string]) {
defer wg.Done()
gotValue, gotError = p.Wait(tc.waitCtx)
}(p)
wg.Wait()
if gotError != nil && !tc.expectError {
t.Fatalf("expected no error, got error %v", gotError.Error())
} else if gotError == nil && tc.expectError {
t.Fatalf("expected error, got no error")
}
if gotValue != tc.expectedValue {
t.Fatalf("expected %v, got %v", tc.expectedValue, gotValue)
}
}
}