From 862db45587725916a784150585df7d725172422b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Tue, 29 Oct 2019 21:19:34 +0100 Subject: [PATCH] Add mising files --- api/client_test.go | 51 ++++++++++++++++++++++++++++++++++++++++++++++ api/fake_http.go | 37 +++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+) create mode 100644 api/client_test.go create mode 100644 api/fake_http.go diff --git a/api/client_test.go b/api/client_test.go new file mode 100644 index 000000000..4d7c64917 --- /dev/null +++ b/api/client_test.go @@ -0,0 +1,51 @@ +package api + +import ( + "bytes" + "fmt" + "io/ioutil" + "reflect" + "testing" +) + +func eq(t *testing.T, got interface{}, expected interface{}) { + t.Helper() + if !reflect.DeepEqual(got, expected) { + t.Errorf("expected: %v, got: %v", expected, got) + } +} + +func TestGraphQL(t *testing.T) { + http := &FakeHTTP{} + client := NewClient( + ReplaceTripper(http), + AddHeader("Authorization", "token OTOKEN"), + ) + + vars := map[string]interface{}{"name": "Mona"} + response := struct { + Viewer struct { + Login string + } + }{} + + http.StubResponse(200, bytes.NewBufferString(`{"data":{"viewer":{"login":"hubot"}}}`)) + err := client.GraphQL("QUERY", vars, &response) + eq(t, err, nil) + eq(t, response.Viewer.Login, "hubot") + + req := http.Requests[0] + reqBody, _ := ioutil.ReadAll(req.Body) + eq(t, string(reqBody), `{"query":"QUERY","variables":{"name":"Mona"}}`) + eq(t, req.Header.Get("Authorization"), "token OTOKEN") +} + +func TestGraphQLError(t *testing.T) { + http := &FakeHTTP{} + client := NewClient(ReplaceTripper(http)) + + response := struct{}{} + http.StubResponse(200, bytes.NewBufferString(`{"errors":[{"message":"OH NO"}]}`)) + err := client.GraphQL("", nil, &response) + eq(t, err, fmt.Errorf("graphql error: 'OH NO'")) +} diff --git a/api/fake_http.go b/api/fake_http.go new file mode 100644 index 000000000..96e38aab3 --- /dev/null +++ b/api/fake_http.go @@ -0,0 +1,37 @@ +package api + +import ( + "fmt" + "io" + "io/ioutil" + "net/http" +) + +// FakeHTTP provides a mechanism by which to stub HTTP responses through +type FakeHTTP struct { + // Requests stores references to sequental requests that RoundTrip has received + Requests []*http.Request + count int + responseStubs []*http.Response +} + +// StubResponse pre-records an HTTP response +func (f *FakeHTTP) StubResponse(status int, body io.Reader) { + resp := &http.Response{ + StatusCode: status, + Body: ioutil.NopCloser(body), + } + f.responseStubs = append(f.responseStubs, resp) +} + +// RoundTrip satisfies http.RoundTripper +func (f *FakeHTTP) RoundTrip(req *http.Request) (*http.Response, error) { + if len(f.responseStubs) <= f.count { + return nil, fmt.Errorf("FakeHTTP: missing response stub for request %d", f.count) + } + resp := f.responseStubs[f.count] + f.count++ + resp.Request = req + f.Requests = append(f.Requests, req) + return resp, nil +}