|
| 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 | +} |
0 commit comments