-
Notifications
You must be signed in to change notification settings - Fork 114
/
Copy pathgout_newopt_timeout_and_global_test.go
100 lines (78 loc) · 2.28 KB
/
gout_newopt_timeout_and_global_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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
package gout
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
)
func setupDataFlow(t *testing.T) *gin.Engine {
router := gin.New()
router.GET("/timeout", func(c *gin.Context) {
ctx := c.Request.Context()
select {
case <-ctx.Done():
fmt.Printf("setTimeout done\n")
case <-time.After(2 * time.Second):
assert.Fail(t, "test timeout fail")
}
})
router.GET("/setdebug", func(c *gin.Context) {
c.String(200, "setdebug")
})
return router
}
func Test_Global_SetTimeout(t *testing.T) {
router := setupDataFlow(t)
const (
longTimeout = 400
middleTimeout = 300
shortTimeout = 200
)
ts := httptest.NewServer(http.HandlerFunc(router.ServeHTTP))
defer ts.Close()
// 只设置timeout
SetTimeout(shortTimeout * time.Millisecond) //设置全局超时时间
err := GET(ts.URL + "/timeout").Do()
// 期望的结果是返回错误
assert.Error(t, err)
ctx, cancel := context.WithTimeout(context.Background(), longTimeout*time.Millisecond)
defer cancel()
s := time.Now()
SetTimeout(shortTimeout * time.Millisecond) // 设置全局超时时间
err = GET(ts.URL + "/timeout").
WithContext(ctx).
Do()
assert.Error(t, err)
assert.LessOrEqual(t, time.Since(s), shortTimeout*time.Millisecond+time.Millisecond*50)
SetTimeout(time.Duration(0))
}
func Test_NewWithOpt_Timeout(t *testing.T) {
router := setupDataFlow(t)
const (
longTimeout = 400
middleTimeout = 300
shortTimeout = 200
)
ts := httptest.NewServer(http.HandlerFunc(router.ServeHTTP))
defer ts.Close()
// 只设置timeout
greq := NewWithOpt(WithTimeout(shortTimeout * time.Millisecond)) //设置全局超时时间
err := greq.GET(ts.URL + "/timeout").Do()
// 期望的结果是返回错误
assert.Error(t, err)
// 使用互斥api的原则,后面的覆盖前面的
// 这里是WithContext生效, 预期超时时间400ms
ctx, cancel := context.WithTimeout(context.Background(), longTimeout*time.Millisecond)
defer cancel()
s := time.Now()
greq = NewWithOpt(WithTimeout(shortTimeout * time.Millisecond)) // 设置全局超时时间
err = greq.GET(ts.URL + "/timeout").
WithContext(ctx).
Do()
assert.Error(t, err)
assert.LessOrEqual(t, time.Since(s), shortTimeout*time.Millisecond+time.Millisecond*50)
}