This repository has been archived by the owner on Feb 7, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcontext_test.go
78 lines (75 loc) · 1.84 KB
/
context_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
package chatbase
import (
"context"
"errors"
"testing"
"time"
)
func TestResultWithContext(t *testing.T) {
t.Run("default", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
result, err := resultWithContext(ctx, func() (interface{}, error) {
time.Sleep(time.Second)
return 12345, nil
})
if err != nil {
t.Errorf("Unexpected error %v", err)
}
if result != 12345 {
t.Errorf("Unexpected result %v", result)
}
})
t.Run("error", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
result, err := resultWithContext(ctx, func() (interface{}, error) {
time.Sleep(time.Second)
return nil, errors.New("broke")
})
if err == nil {
t.Error("Expected error, got nil")
}
if result != nil {
t.Errorf("Unexpected result %v", result)
}
})
t.Run("timeout", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
result, err := resultWithContext(ctx, func() (interface{}, error) {
time.Sleep(time.Minute)
return 12345, nil
})
if err == nil {
t.Error("Expected error, got nil")
}
if result != nil {
t.Errorf("Unexpected result %v", result)
}
})
}
func TestWithContext(t *testing.T) {
t.Run("default", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Minute)
defer cancel()
err := withContext(ctx, func() error {
time.Sleep(time.Second)
return nil
})
if err != nil {
t.Errorf("Unexpected error %v", err)
}
})
t.Run("timeout", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
err := withContext(ctx, func() error {
time.Sleep(time.Minute)
return nil
})
if err == nil {
t.Error("Expected error, got nil")
}
})
}