forked from grafana/grafana-api-golang-client
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mock.go
46 lines (37 loc) · 861 Bytes
/
mock.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
package gapi
import (
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"testing"
)
type mockServer struct {
code int
server *httptest.Server
}
func (m *mockServer) Close() {
m.server.Close()
}
func gapiTestTools(t *testing.T, code int, body string) (*mockServer, *Client) {
t.Helper()
mock := &mockServer{
code: code,
}
mock.server = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(mock.code)
w.Header().Set("Content-Type", "application/json")
fmt.Fprint(w, body)
}))
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)
}
return mock, client
}