-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathresponse_test.go
107 lines (96 loc) · 2.32 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
100
101
102
103
104
105
106
107
package gohttp
import (
"bytes"
"compress/flate"
"compress/gzip"
"errors"
"io"
"net/http"
"os"
"testing"
)
type errReader int
func (errReader) Read(p []byte) (n int, err error) {
return 0, errors.New("test error")
}
func (errReader) Close() error { return nil }
func TestBytes(t *testing.T) {
r, err := buildResponse(&http.Response{Body: errReader(0)})
if err != nil {
t.Fatal(err)
}
if b := r.Bytes(); b != nil {
t.Error("gave non nil bytes; want nil")
}
if _, err := buildResponse(&http.Response{
Header: http.Header{"Content-Encoding": []string{"gzip"}},
Body: errReader(0),
}); err == nil {
t.Error("gave nil error; want test error")
}
var buf bytes.Buffer
zw := gzip.NewWriter(&buf)
zw.Write([]byte("test"))
zw.Close()
r, err = buildResponse(&http.Response{
Header: http.Header{"Content-Encoding": []string{"gzip"}},
Body: io.NopCloser(&buf),
})
if err != nil {
t.Fatal(err)
}
if b := r.String(); b != "test" {
t.Errorf("expected %q; got %q", "test", b)
}
if b := r.String(); b != "test" { // cached
t.Errorf("expected %q; got %q", "test", b)
}
fw, _ := flate.NewWriter(&buf, -1)
fw.Write([]byte("deflate"))
fw.Close()
r, _ = buildResponse(&http.Response{
Header: http.Header{"Content-Encoding": []string{"deflate"}},
Body: io.NopCloser(&buf),
})
if b := r.String(); b != "deflate" {
t.Errorf("expected %q; got %q", "deflate", b)
}
}
func TestJSON(t *testing.T) {
r, err := buildResponse(&http.Response{Body: io.NopCloser(bytes.NewReader([]byte("-1")))})
if err != nil {
t.Fatal(err)
}
var data uint
if err := r.JSON(&data); err == nil {
t.Error("gave nil error; want error")
}
r, err = buildResponse(&http.Response{Body: errReader(0)})
if err != nil {
t.Fatal(err)
}
if err := r.JSON(nil); err == nil {
t.Error("gave nil error; want error")
}
}
func TestSave(t *testing.T) {
r, _ := buildResponse(&http.Response{Body: io.NopCloser(bytes.NewBufferString("test"))})
if _, err := r.Save(""); err == nil {
t.Error("gave nil error; want error")
}
f, _ := os.CreateTemp("", "test")
f.Close()
defer os.Remove(f.Name())
if n, err := r.Save(f.Name()); err != nil {
t.Fatal(err)
} else if n != 4 {
t.Error(n)
}
b, err := os.ReadFile(f.Name())
if err != nil {
t.Fatal(err)
}
if s := string(b); s != "test" {
t.Errorf("expected %q; got %q", "test", s)
}
}