aboutsummaryrefslogtreecommitdiffstats
path: root/jttp_test.go
blob: 26b0b8d28471695e681dfa748f88cca4d1bade24 (plain) (blame)
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
package jttp_test

import (
	"fmt"
	"net/http"
	"net/http/httptest"
	"net/url"
	"testing"

	"github.com/stretchr/testify/require"

	"git.samanthony.xyz/jttp"
)

type Person struct {
	Name string
	Age  int
}

func do(t *testing.T, handler http.HandlerFunc, method string, wantStatus int) (Person, error) {
	t.Helper()

	srv := httptest.NewServer(handler)
	defer srv.Close()

	url, err := url.Parse(srv.URL)
	require.NoError(t, err)

	clnt := jttp.NewClient(srv.Client())
	req := &http.Request{Method: method, URL: url}
	var person Person
	err = clnt.Do(req, wantStatus, &person)
	return person, err
}

func TestDo(t *testing.T) {
	handler := func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"name": "Alice", "age": 123}`)
	}
	alice, err := do(t, handler, http.MethodGet, http.StatusOK)
	require.NoError(t, err)
	require.Equal(t, Person{"Alice", 123}, alice)
}

func TestDoReqFail(t *testing.T) {
	clnt := jttp.NewClient(&http.Client{})
	req := &http.Request{}
	var alice Person
	err := clnt.Do(req, http.StatusOK, &alice)
	require.Error(t, err)
	require.Contains(t, err.Error(), "http: nil Request.URL")
}

func TestDoBadStatus(t *testing.T) {
	handler := func(w http.ResponseWriter, r *http.Request) {
		w.WriteHeader(201)
		fmt.Fprint(w, `{"name": "Alice", "age": 123}`)
	}
	_, err := do(t, handler, http.MethodGet, 200)
	require.Error(t, err)
	require.Contains(t, err.Error(), "jttp")
	require.Contains(t, err.Error(), "201 Created (expected 200)")
}

func TestDoDecodeFail(t *testing.T) {
	handler := func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprint(w, `{"name": "Alice", "age": "notanumber"}`)
	}
	_, err := do(t, handler, http.MethodGet, http.StatusOK)
	require.Error(t, err)
	require.Contains(t, err.Error(), "json")
	require.Contains(t, err.Error(), "Person.Age")
}