-
Notifications
You must be signed in to change notification settings - Fork 2
/
route4me_test.go
86 lines (76 loc) · 1.95 KB
/
route4me_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
77
78
79
80
81
82
83
84
85
86
package route4me
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
const apiKey = "11111111111111111111111111111111"
func TestNewClient(t *testing.T) {
cli := NewClient(apiKey)
if cli.Client == nil {
t.Error("Client has not been initialized.")
}
if cli.APIKey != apiKey {
t.Error("APIKey has not been assigned.")
}
}
func testClient(code int, body string) (*httptest.Server, *Client) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(code)
read, err := ioutil.ReadAll(r.Body)
if err != nil || len(read) == 0 {
fmt.Fprint(w, body)
} else {
w.Write(read)
}
}))
transport := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(server.URL)
},
}
httpClient := &http.Client{Transport: transport}
client := &Client{Client: httpClient, APIKey: apiKey, BaseURL: "http://example.com"}
return server, client
}
type response struct {
Number int `json:"json"`
}
func TestDecodingGet(t *testing.T) {
server, cli := testClient(200, `{"json":42}`)
defer server.Close()
resp := &response{}
err := cli.Do(http.MethodGet, "/whatever/", &struct{}{}, resp)
if err != nil {
t.Error(err)
}
if resp.Number != 42 {
t.Error("Unmarshalling went wrong")
}
}
func TestDecodingPost(t *testing.T) {
server, cli := testClient(200, `{"json":42}`)
defer server.Close()
resp := &response{}
err := cli.Do(http.MethodPost, "/whatever/", &struct {
Number int `json:"json"`
}{Number: 152}, resp)
if err != nil {
t.Error(err)
}
if resp.Number != 152 {
t.Error("Error occured during unmarshalling")
}
}
func TestDecodingErrors(t *testing.T) {
server, cli := testClient(500, `{"errors":["error#1","error#2"]}`)
defer server.Close()
resp := &response{}
err := cli.Do(http.MethodGet, "/", &struct{}{}, resp)
if err == nil || err.Error() != "error#1,error#2" {
t.Error("Expecting error 'error#1,error#2', got: ", err.Error())
}
}