Skip to content

Commit 862db45

Browse files
committed
Add mising files
1 parent 343ccaf commit 862db45

File tree

2 files changed

+88
-0
lines changed

2 files changed

+88
-0
lines changed

api/client_test.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package api
2+
3+
import (
4+
"bytes"
5+
"fmt"
6+
"io/ioutil"
7+
"reflect"
8+
"testing"
9+
)
10+
11+
func eq(t *testing.T, got interface{}, expected interface{}) {
12+
t.Helper()
13+
if !reflect.DeepEqual(got, expected) {
14+
t.Errorf("expected: %v, got: %v", expected, got)
15+
}
16+
}
17+
18+
func TestGraphQL(t *testing.T) {
19+
http := &FakeHTTP{}
20+
client := NewClient(
21+
ReplaceTripper(http),
22+
AddHeader("Authorization", "token OTOKEN"),
23+
)
24+
25+
vars := map[string]interface{}{"name": "Mona"}
26+
response := struct {
27+
Viewer struct {
28+
Login string
29+
}
30+
}{}
31+
32+
http.StubResponse(200, bytes.NewBufferString(`{"data":{"viewer":{"login":"hubot"}}}`))
33+
err := client.GraphQL("QUERY", vars, &response)
34+
eq(t, err, nil)
35+
eq(t, response.Viewer.Login, "hubot")
36+
37+
req := http.Requests[0]
38+
reqBody, _ := ioutil.ReadAll(req.Body)
39+
eq(t, string(reqBody), `{"query":"QUERY","variables":{"name":"Mona"}}`)
40+
eq(t, req.Header.Get("Authorization"), "token OTOKEN")
41+
}
42+
43+
func TestGraphQLError(t *testing.T) {
44+
http := &FakeHTTP{}
45+
client := NewClient(ReplaceTripper(http))
46+
47+
response := struct{}{}
48+
http.StubResponse(200, bytes.NewBufferString(`{"errors":[{"message":"OH NO"}]}`))
49+
err := client.GraphQL("", nil, &response)
50+
eq(t, err, fmt.Errorf("graphql error: 'OH NO'"))
51+
}

api/fake_http.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package api
2+
3+
import (
4+
"fmt"
5+
"io"
6+
"io/ioutil"
7+
"net/http"
8+
)
9+
10+
// FakeHTTP provides a mechanism by which to stub HTTP responses through
11+
type FakeHTTP struct {
12+
// Requests stores references to sequental requests that RoundTrip has received
13+
Requests []*http.Request
14+
count int
15+
responseStubs []*http.Response
16+
}
17+
18+
// StubResponse pre-records an HTTP response
19+
func (f *FakeHTTP) StubResponse(status int, body io.Reader) {
20+
resp := &http.Response{
21+
StatusCode: status,
22+
Body: ioutil.NopCloser(body),
23+
}
24+
f.responseStubs = append(f.responseStubs, resp)
25+
}
26+
27+
// RoundTrip satisfies http.RoundTripper
28+
func (f *FakeHTTP) RoundTrip(req *http.Request) (*http.Response, error) {
29+
if len(f.responseStubs) <= f.count {
30+
return nil, fmt.Errorf("FakeHTTP: missing response stub for request %d", f.count)
31+
}
32+
resp := f.responseStubs[f.count]
33+
f.count++
34+
resp.Request = req
35+
f.Requests = append(f.Requests, req)
36+
return resp, nil
37+
}

0 commit comments

Comments
 (0)