Esempio n. 1
0
func TestHTTPClient(t *testing.T) {
	var (
		decode    = func(r io.Reader) (interface{}, error) { return struct{}{}, nil }
		encode    = func(w io.Writer, response interface{}) error { return nil }
		headers   = make(chan string, 1)
		headerKey = "X-Foo"
		headerVal = "abcde"
	)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		headers <- r.Header.Get(headerKey)
		w.WriteHeader(http.StatusOK)
	}))

	client := httptransport.Client{
		Method:     "GET",
		URL:        mustParse(server.URL),
		Context:    context.Background(),
		DecodeFunc: decode,
		EncodeFunc: encode,
		Before:     []httptransport.RequestFunc{httptransport.SetRequestHeader(headerKey, headerVal)},
	}

	_, err := client.Endpoint()(context.Background(), struct{}{})
	if err != nil {
		t.Fatal(err)
	}

	var have string
	select {
	case have = <-headers:
	case <-time.After(time.Millisecond):
		t.Fatalf("timeout waiting for %s", headerKey)
	}
	if want := headerVal; want != have {
		t.Errorf("want %q, have %q", want, have)
	}
}
Esempio n. 2
0
func TestHTTPClient(t *testing.T) {
	var (
		testbody = "testbody"
		encode   = func(context.Context, *http.Request, interface{}) error { return nil }
		decode   = func(_ context.Context, r *http.Response) (interface{}, error) {
			buffer := make([]byte, len(testbody))
			r.Body.Read(buffer)
			return TestResponse{r.Body, string(buffer)}, nil
		}
		headers   = make(chan string, 1)
		headerKey = "X-Foo"
		headerVal = "abcde"
	)

	server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		headers <- r.Header.Get(headerKey)
		w.WriteHeader(http.StatusOK)
		w.Write([]byte(testbody))
	}))

	client := httptransport.NewClient(
		"GET",
		mustParse(server.URL),
		encode,
		decode,
		httptransport.SetClientBefore(httptransport.SetRequestHeader(headerKey, headerVal)),
	)

	res, err := client.Endpoint()(context.Background(), struct{}{})
	if err != nil {
		t.Fatal(err)
	}

	var have string
	select {
	case have = <-headers:
	case <-time.After(time.Millisecond):
		t.Fatalf("timeout waiting for %s", headerKey)
	}
	// Check that Request Header was successfully received
	if want := headerVal; want != have {
		t.Errorf("want %q, have %q", want, have)
	}

	// Check that the response was successfully decoded
	response, ok := res.(TestResponse)
	if !ok {
		t.Fatal("response should be TestResponse")
	}
	if want, have := testbody, response.String; want != have {
		t.Errorf("want %q, have %q", want, have)
	}

	// Check that response body was closed
	b := make([]byte, 1)
	_, err = response.Body.Read(b)
	if err == nil {
		t.Fatal("wanted error, got none")
	}
	if doNotWant, have := io.EOF, err; doNotWant == have {
		t.Errorf("do not want %q, have %q", doNotWant, have)
	}
}