-
-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
client_test.go
63 lines (51 loc) · 1.46 KB
/
client_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
package client
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
var defaultCtx = context.Background()
type testValue struct {
Firstname string `json:"firstname"`
}
func TestClientJSON(t *testing.T) {
expectedJSON := testValue{Firstname: "Makis"}
app := http.NewServeMux()
app.HandleFunc("/send", sendJSON(t, expectedJSON))
var irisGotJSON testValue
app.HandleFunc("/read", readJSON(t, &irisGotJSON, &expectedJSON))
srv := httptest.NewServer(app)
client := New(BaseURL(srv.URL))
// Test ReadJSON (read from server).
var got testValue
if err := client.ReadJSON(defaultCtx, &got, http.MethodGet, "/send", nil); err != nil {
t.Fatal(err)
}
// Test JSON (send to server).
resp, err := client.JSON(defaultCtx, http.MethodPost, "/read", expectedJSON)
if err != nil {
t.Fatal(err)
}
client.DrainResponseBody(resp)
}
func sendJSON(t *testing.T, v interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
if err := json.NewEncoder(w).Encode(v); err != nil {
t.Fatal(err)
}
}
}
func readJSON(t *testing.T, ptr interface{}, expected interface{}) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if err := json.NewDecoder(r.Body).Decode(ptr); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(ptr, expected) {
t.Fatalf("expected to read json: %#+v but got: %#+v", ptr, expected)
}
}
}