-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
response_test.go
99 lines (81 loc) · 2.48 KB
/
response_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
package x_test
import (
"context"
"fmt"
"io"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"github.com/hashicorp/go-retryablehttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"gitlab.com/tozd/go/x"
)
const responseBody = "Hello, client\n"
func TestRetryableResponseSimple(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprint(w, responseBody)
}))
defer ts.Close()
ctx := context.Background()
client := retryablehttp.NewClient()
req, err := retryablehttp.NewRequestWithContext(ctx, http.MethodGet, ts.URL, nil)
require.NoError(t, err)
require.NotNil(t, req)
res, err := x.NewRetryableResponse(client, req)
require.NoError(t, err, "% -+#.1v", err)
require.NotNil(t, res)
defer res.Close()
assert.Equal(t, int64(14), res.ContentLength)
assert.Equal(t, int64(14), res.Size())
response, err := io.ReadAll(res)
require.NoError(t, err)
assert.Equal(t, responseBody, string(response))
}
func TestRetryableResponseRetry(t *testing.T) {
t.Parallel()
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if reqRange := r.Header.Get("Range"); reqRange != "" {
if assert.True(t, strings.HasPrefix(reqRange, "bytes=")) {
reqRange = strings.TrimPrefix(reqRange, "bytes=")
rs := strings.Split(reqRange, "-")
if assert.Len(t, rs, 2) {
end := rs[1]
assert.Equal(t, "", end)
start, err := strconv.Atoi(rs[0])
if assert.NoError(t, err) {
assert.Equal(t, 6, start)
rest := responseBody[start:]
w.Header().Set("Content-Length", strconv.Itoa(len(rest)))
w.WriteHeader(http.StatusPartialContent)
// Send the rest.
fmt.Fprint(w, rest)
}
}
}
} else {
w.Header().Set("Content-Length", strconv.Itoa(len(responseBody)))
w.WriteHeader(http.StatusOK)
// Send only the first 6 bytes.
fmt.Fprint(w, responseBody[0:6])
}
}))
defer ts.Close()
ctx := context.Background()
client := retryablehttp.NewClient()
req, err := retryablehttp.NewRequestWithContext(ctx, http.MethodGet, ts.URL, nil)
require.NoError(t, err)
require.NotNil(t, req)
res, err := x.NewRetryableResponse(client, req)
require.NoError(t, err, "% -+#.1v", err)
require.NotNil(t, res)
defer res.Close()
assert.Equal(t, int64(14), res.ContentLength)
assert.Equal(t, int64(14), res.Size())
data, err := io.ReadAll(res)
require.NoError(t, err)
assert.Equal(t, responseBody, string(data))
}