-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathasyn_call_test.go
67 lines (62 loc) · 1.58 KB
/
asyn_call_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
package concurrency
import (
"context"
"errors"
"fmt"
"testing"
"time"
)
var task = func(ctx context.Context) TaskResult {
time.Sleep(time.Second * 3)
return TaskResult{"OK", nil}
}
func TestHappyPath(t *testing.T) {
startTime := time.Now()
retStub := AsynExecutor(context.TODO(), task, 5000)
if time.Since(startTime).Milliseconds() > 2 {
t.Error("It is not asynchronous call.")
}
fmt.Println("nonblocking")
ret := retStub.GetResult()
if ret.Err != nil {
t.Error(ret.Err)
}
if time.Since(startTime).Microseconds() < 3000 {
t.Error("It is not unexpected execution time.")
}
fmt.Println(ret.Result.(string), ret.Err)
}
func TestTimeoutPath(t *testing.T) {
startTime := time.Now()
retStub := AsynExecutor(context.TODO(), task, 100)
if time.Since(startTime).Milliseconds() > 2 {
t.Error("It is not asynchronous call.")
}
fmt.Println("nonblocking")
ret := retStub.GetResult()
if ret.Err == nil {
t.Error("It is not unexpected execution time.")
}
if !errors.Is(ret.Err, ErrTimeout) {
t.Error("It is unexpected error", ret.Err)
}
fmt.Println(ret.Result, ret.Err)
}
func TestCancelPath(t *testing.T) {
startTime := time.Now()
ctx, cancelFn := context.WithCancel(context.Background())
retStub := AsynExecutor(ctx, task, 1)
if time.Since(startTime).Milliseconds() > 2 {
t.Error("It is not asynchronous call.")
}
fmt.Println("nonblocking")
cancelFn()
ret := retStub.GetResult()
if ret.Err == nil {
t.Error("It is not unexpected execution time.")
}
if !errors.Is(ret.Err, ErrCancelled) {
t.Error("It is unexpected error", ret.Err)
}
fmt.Println(ret.Result, ret.Err)
}