|
| 1 | +package handler_test |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "net/http/httptest" |
| 6 | + "strings" |
| 7 | + "testing" |
| 8 | + |
| 9 | + "github.com/graphql-go/graphql/testutil" |
| 10 | + "github.com/graphql-go/handler" |
| 11 | +) |
| 12 | + |
| 13 | +func TestRenderGraphiQL(t *testing.T) { |
| 14 | + cases := map[string]struct { |
| 15 | + graphiqlEnabled bool |
| 16 | + accept string |
| 17 | + expectedStatusCode int |
| 18 | + expectedContentType string |
| 19 | + expectedBodyContains string |
| 20 | + }{ |
| 21 | + "renders GraphiQL": { |
| 22 | + graphiqlEnabled: true, |
| 23 | + accept: "text/html", |
| 24 | + expectedStatusCode: http.StatusOK, |
| 25 | + expectedContentType: "text/html; charset=utf-8", |
| 26 | + expectedBodyContains: "<!DOCTYPE html>", |
| 27 | + }, |
| 28 | + "doesn't render graphiQL if turned off": { |
| 29 | + graphiqlEnabled: false, |
| 30 | + accept: "text/html", |
| 31 | + expectedStatusCode: http.StatusOK, |
| 32 | + expectedContentType: "application/json; charset=utf-8", |
| 33 | + }, |
| 34 | + "doesn't render GraphiQL if Content-Type application/json is present": { |
| 35 | + graphiqlEnabled: true, |
| 36 | + accept: "application/json,text/html", |
| 37 | + expectedStatusCode: http.StatusOK, |
| 38 | + expectedContentType: "application/json; charset=utf-8", |
| 39 | + }, |
| 40 | + } |
| 41 | + |
| 42 | + for tcID, tc := range cases { |
| 43 | + t.Run(tcID, func(t *testing.T) { |
| 44 | + req, err := http.NewRequest(http.MethodGet, "", nil) |
| 45 | + if err != nil { |
| 46 | + t.Error(err) |
| 47 | + } |
| 48 | + |
| 49 | + req.Header.Set("Accept", tc.accept) |
| 50 | + |
| 51 | + h := handler.New(&handler.Config{ |
| 52 | + Schema: &testutil.StarWarsSchema, |
| 53 | + GraphiQL: tc.graphiqlEnabled, |
| 54 | + }) |
| 55 | + |
| 56 | + rr := httptest.NewRecorder() |
| 57 | + |
| 58 | + h.ServeHTTP(rr, req) |
| 59 | + resp := rr.Result() |
| 60 | + |
| 61 | + statusCode := resp.StatusCode |
| 62 | + if statusCode != tc.expectedStatusCode { |
| 63 | + t.Fatalf("%s: wrong status code, expected %v, got %v", tcID, tc.expectedStatusCode, statusCode) |
| 64 | + } |
| 65 | + |
| 66 | + contentType := resp.Header.Get("Content-Type") |
| 67 | + if contentType != tc.expectedContentType { |
| 68 | + t.Fatalf("%s: wrong content type, expected %s, got %s", tcID, tc.expectedContentType, contentType) |
| 69 | + } |
| 70 | + |
| 71 | + body := rr.Body.String() |
| 72 | + if !strings.Contains(body, tc.expectedBodyContains) { |
| 73 | + t.Fatalf("%s: wrong body, expected %s to contain %s", tcID, body, tc.expectedBodyContains) |
| 74 | + } |
| 75 | + }) |
| 76 | + } |
| 77 | +} |
0 commit comments