This repository has been archived by the owner on Aug 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpclient_test.go
76 lines (65 loc) · 1.94 KB
/
httpclient_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
package otgo_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"testing"
otgo "github.com/open-trust/ot-go-lib"
"github.com/stretchr/testify/assert"
)
func TestHTTPClient(t *testing.T) {
t.Run("DefaultHTTPClient", func(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
if r.Method == "POST" {
_, err := io.Copy(w, r.Body)
if err != nil {
panic(err)
}
} else {
w.Write([]byte(`{"result": "ok"}`))
}
}))
defer ts.Close()
res := map[string]string{}
err := otgo.DefaultHTTPClient.Do(context.Background(), "GET", ts.URL, nil, nil, &res)
assert.Nil(err)
assert.Equal("ok", res["result"])
res = map[string]string{}
err = otgo.DefaultHTTPClient.Do(context.Background(), "POST", ts.URL, nil, map[string]string{"result": "OK"}, &res)
assert.Nil(err)
assert.Equal("OK", res["result"])
})
t.Run("WithUA & WithToken", func(t *testing.T) {
assert := assert.New(t)
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.WriteHeader(200)
m := map[string]string{}
for k, v := range r.Header {
m[k] = v[0]
}
b, err := json.Marshal(m)
if err != nil {
panic(err)
}
w.Write(b)
}))
defer ts.Close()
cli := otgo.DefaultHTTPClient
res := map[string]string{}
cli.Header.Set("User-Agent", "UA123")
err := cli.Do(context.Background(), "GET", ts.URL, nil, nil, &res)
assert.Nil(err)
assert.Equal("UA123", res["User-Agent"])
res = map[string]string{}
err = cli.Do(context.Background(), "GET", ts.URL, otgo.AddTokenToHeader(http.Header{}, "token456"), nil, &res)
assert.Nil(err)
assert.Equal("UA123", res["User-Agent"])
assert.Equal("Bearer token456", res["Authorization"])
})
}