netboxgo/devices_test.go

74 lines
1.3 KiB
Go
Raw Normal View History

package netboxgo_test
import (
"bytes"
"context"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"testing"
. "git.kcbark.net/kc/netboxgo"
)
type fakeClient struct {
q url.Values
h *http.Client
}
func newFakeClient() *fakeClient {
return &fakeClient{q: url.Values{}, h: &http.Client{}}
}
func (c *fakeClient) prepare(path string, jsonfile string) {
u, err := url.Parse(path)
if err != nil {
panic(err)
}
b, err := ioutil.ReadFile(jsonfile)
if err != nil {
log.Fatalf("failed to read json file: %q: %+v", jsonfile, err)
}
newFakeHTTPClient := NewTestClient(func(req *http.Request) *http.Response {
return &http.Response{
StatusCode: 200,
Body: io.NopCloser(bytes.NewBuffer(b)),
Header: make(http.Header),
}
})
c.q = u.Query()
c.h = newFakeHTTPClient
}
func NewTestClient(fn RoundTripFunc) *http.Client {
return &http.Client{
Transport: RoundTripFunc(fn),
}
}
type RoundTripFunc func(req *http.Request) *http.Response
func (f RoundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) {
return f(req), nil
}
func TestDevicesList(t *testing.T) {
c := newFakeClient()
c.prepare("/dcim/devices", "./testdata/dcim_devices_list.json")
nb, err := NewClient("tokenloken", c.h)
ok(t, err)
ctx := context.Background()
devices, err := nb.Devices.List(ctx, nil)
ok(t, err)
equals(t, 10, len(devices.Results))
}