-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathdecode_test.go
More file actions
105 lines (90 loc) · 2.25 KB
/
decode_test.go
File metadata and controls
105 lines (90 loc) · 2.25 KB
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
101
102
103
104
105
package httpx
import (
"net/http"
"net/http/httptest"
"testing"
"github.com/imroc/req/v3"
)
func TestRawKindAndDecode(t *testing.T) {
if rawKindOf[string]() != rawString {
t.Fatalf("expected rawString")
}
if rawKindOf[[]byte]() != rawBytes {
t.Fatalf("expected rawBytes")
}
if rawKindOf[[]int]() != rawNone {
t.Fatalf("expected rawNone for slice")
}
if rawKindOf[int]() != rawNone {
t.Fatalf("expected rawNone")
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("hello"))
}))
t.Cleanup(srv.Close)
resp, err := req.C().R().Get(srv.URL)
if err != nil {
t.Fatalf("request failed: %v", err)
}
if got := decodeRaw[string](resp); got != "hello" {
t.Fatalf("decode string = %q", got)
}
if got := decodeRaw[[]byte](resp); string(got) != "hello" {
t.Fatalf("decode bytes = %q", string(got))
}
if got := decodeRaw[int](resp); got != 0 {
t.Fatalf("decode int = %d", got)
}
}
func TestEnsureNonNil(t *testing.T) {
var p *int
ensureNonNil(p)
var s []int
ensureNonNil(&s)
if s == nil {
t.Fatalf("expected slice initialized")
}
var m map[string]int
ensureNonNil(&m)
if m == nil {
t.Fatalf("expected map initialized")
}
}
func TestIsEmptyBody(t *testing.T) {
if isEmptyBody(nil) {
t.Fatalf("expected false for nil response")
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
t.Cleanup(srv.Close)
resp, err := req.C().R().Get(srv.URL)
if err != nil {
t.Fatalf("request failed: %v", err)
}
if !isEmptyBody(resp) {
t.Fatalf("expected empty body")
}
srv2 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte("data"))
}))
t.Cleanup(srv2.Close)
resp2, err := req.C().R().Get(srv2.URL)
if err != nil {
t.Fatalf("request failed: %v", err)
}
if isEmptyBody(resp2) {
t.Fatalf("expected non-empty body")
}
srv3 := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_, _ = w.Write([]byte(" "))
}))
t.Cleanup(srv3.Close)
resp3, err := req.C().R().Get(srv3.URL)
if err != nil {
t.Fatalf("request failed: %v", err)
}
if !isEmptyBody(resp3) {
t.Fatalf("expected empty body for whitespace")
}
}