forked from grafana/amixr-api-go-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_test.go
80 lines (64 loc) · 1.68 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package aapi
import (
"fmt"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// Tests should register handlers on mux which provide mock responses for the API method being tested.
func setup(t *testing.T) (*http.ServeMux, *httptest.Server, *Client) {
mux := http.NewServeMux()
server := httptest.NewServer(mux)
c, err := New(server.URL, "token")
if err != nil {
server.Close()
t.Fatalf("Failed to create client: %v", err)
}
return mux, server, c
}
func teardown(server *httptest.Server) {
server.Close()
}
func testRequestMethod(t *testing.T, r *http.Request, want string) {
if got := r.Method; got != want {
t.Errorf("Request method: %s, want %s", got, want)
}
}
func TestNewClient(t *testing.T) {
c, err := New("base_url", "token")
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
expectedBaseURL := "base_url/" + apiVersionPath
if c.BaseURL().String() != expectedBaseURL {
t.Errorf("NewClient BaseURL is %s, want %s", c.BaseURL().String(), expectedBaseURL)
}
}
func TestCheckResponse(t *testing.T) {
c, err := New("base_url", "token")
if err != nil {
t.Fatalf("Failed to create client: %v", err)
}
req, err := c.NewRequest("GET", "test", nil)
if err != nil {
t.Fatalf("Failed to create request: %v", err)
}
resp := &http.Response{
Request: req.Request,
StatusCode: http.StatusBadRequest,
Body: ioutil.NopCloser(strings.NewReader(`
{
"detail": "error"
}`)),
}
errResp := CheckResponse(resp)
if errResp == nil {
t.Fatal("Expected error response.")
}
want := fmt.Sprintf("GET ://%s: 400 {detail: error}", req.URL)
if errResp.Error() != want {
t.Errorf("Expected error: %s, got %s", want, errResp.Error())
}
}