iris/x/client/client_test.go

64 lines
1.5 KiB
Go
Raw Normal View History

2022-02-25 19:17:02 +01:00
package client
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
2022-02-25 19:17:02 +01:00
"reflect"
"testing"
)
var defaultCtx = context.Background()
2022-02-25 19:17:02 +01:00
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))
2022-02-25 19:17:02 +01:00
var irisGotJSON testValue
app.HandleFunc("/read", readJSON(t, &irisGotJSON, &expectedJSON))
2022-02-25 19:17:02 +01:00
srv := httptest.NewServer(app)
2022-02-25 19:17:02 +01:00
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 {
2022-02-25 19:17:02 +01:00
t.Fatal(err)
}
// Test JSON (send to server).
resp, err := client.JSON(defaultCtx, http.MethodPost, "/read", expectedJSON)
2022-02-25 19:17:02 +01:00
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 {
2022-02-25 19:17:02 +01:00
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 {
2022-02-25 19:17:02 +01:00
t.Fatal(err)
}
if !reflect.DeepEqual(ptr, expected) {
t.Fatalf("expected to read json: %#+v but got: %#+v", ptr, expected)
}
}
}