Debian Codegraph @

v3/pkg/grabtest/assert.go

raw symbols SCIP
1 package grabtest
2
3 import (
4 "bytes"
5 "crypto/sha256"
6 "fmt"
7 "io"
8 "io/ioutil"
9 "net/http"
10 "testing"
11 )
12
13 func AssertHTTPResponseStatusCode(t *testing.T, resp *http.Response, expect int) (ok bool) {
14 if resp.StatusCode != expect {
15 t.Errorf("expected status code: %d, got: %d", expect, resp.StatusCode)
16 return
17 }
18 ok = true
19 return true
20 }
21
22 func AssertHTTPResponseHeader(t *testing.T, resp *http.Response, key, format string, a ...interface{}) (ok bool) {
23 expect := fmt.Sprintf(format, a...)
24 actual := resp.Header.Get(key)
25 if actual != expect {
26 t.Errorf("expected header %s: %s, got: %s", key, expect, actual)
27 return
28 }
29 ok = true
30 return
31 }
32
33 func AssertHTTPResponseContentLength(t *testing.T, resp *http.Response, n int64) (ok bool) {
34 ok = true
35 if resp.ContentLength != n {
36 ok = false
37 t.Errorf("expected header Content-Length: %d, got: %d", n, resp.ContentLength)
38 }
39 if !AssertHTTPResponseBodyLength(t, resp, n) {
40 ok = false
41 }
42 return
43 }
44
45 func AssertHTTPResponseBodyLength(t *testing.T, resp *http.Response, n int64) (ok bool) {
46 defer func() {
47 if err := resp.Body.Close(); err != nil {
48 panic(err)
49 }
50 }()
51 b, err := ioutil.ReadAll(resp.Body)
52 if err != nil {
53 panic(err)
54 }
55 if int64(len(b)) != n {
56 ok = false
57 t.Errorf("expected body length: %d, got: %d", n, len(b))
58 }
59 return
60 }
61
62 func MustHTTPNewRequest(method, url string, body io.Reader) *http.Request {
63 req, err := http.NewRequest(method, url, body)
64 if err != nil {
65 panic(err)
66 }
67 return req
68 }
69
70 func MustHTTPDo(req *http.Request) *http.Response {
71 resp, err := http.DefaultClient.Do(req)
72 if err != nil {
73 panic(err)
74 }
75 return resp
76 }
77
78 func MustHTTPDoWithClose(req *http.Request) *http.Response {
79 resp := MustHTTPDo(req)
80 if _, err := io.Copy(ioutil.Discard, resp.Body); err != nil {
81 panic(err)
82 }
83 if err := resp.Body.Close(); err != nil {
84 panic(err)
85 }
86 return resp
87 }
88
89 func AssertSHA256Sum(t *testing.T, sum []byte, r io.Reader) (ok bool) {
90 h := sha256.New()
91 if _, err := io.Copy(h, r); err != nil {
92 panic(err)
93 }
94 computed := h.Sum(nil)
95 ok = bytes.Equal(sum, computed)
96 if !ok {
97 t.Errorf(
98 "expected checksum: %s, got: %s",
99 MustHexEncodeString(sum),
100 MustHexEncodeString(computed),
101 )
102 }
103 return
104 }