forked from grafana/grafana-api-golang-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock_test.go
68 lines (56 loc) · 1.39 KB
/
mock_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
package gapi
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
type mockServerCall struct {
code int
body string
}
type mockServer struct {
upcomingCalls []mockServerCall
executedCalls []mockServerCall
server *httptest.Server
}
func gapiTestTools(t *testing.T, code int, body string) *Client {
t.Helper()
return gapiTestToolsFromCalls(t, []mockServerCall{{code, body}})
}
func gapiTestToolsFromCalls(t *testing.T, calls []mockServerCall) *Client {
t.Helper()
mock := &mockServer{
upcomingCalls: calls,
}
mock.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if len(mock.upcomingCalls) == 0 {
t.Fatalf("unexpected call to %s %s", r.Method, r.URL)
}
call := mock.upcomingCalls[0]
if len(calls) > 1 {
mock.upcomingCalls = mock.upcomingCalls[1:]
} else {
mock.upcomingCalls = nil
}
w.WriteHeader(call.code)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, call.body)
mock.executedCalls = append(mock.executedCalls, call)
}))
tr := &http.Transport{
Proxy: func(req *http.Request) (*url.URL, error) {
return url.Parse(mock.server.URL)
},
}
httpClient := &http.Client{Transport: tr}
client, err := New("http://my-grafana.com", Config{APIKey: "my-key", Client: httpClient})
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
mock.server.Close()
})
return client
}