github.com/abdfnx/gh-api@v0.0.0-20210414084727-f5432eec23b8/api/client_test.go (about) 1 package api 2 3 import ( 4 "bytes" 5 "errors" 6 "io/ioutil" 7 "net/http" 8 "testing" 9 10 "github.com/abdfnx/gh-api/pkg/httpmock" 11 "github.com/stretchr/testify/assert" 12 ) 13 14 func TestGraphQL(t *testing.T) { 15 http := &httpmock.Registry{} 16 client := NewClient( 17 ReplaceTripper(http), 18 AddHeader("Authorization", "token OTOKEN"), 19 ) 20 21 vars := map[string]interface{}{"name": "Mona"} 22 response := struct { 23 Viewer struct { 24 Login string 25 } 26 }{} 27 28 http.Register( 29 httpmock.GraphQL("QUERY"), 30 httpmock.StringResponse(`{"data":{"viewer":{"login":"hubot"}}}`), 31 ) 32 33 err := client.GraphQL("github.com", "QUERY", vars, &response) 34 assert.NoError(t, err) 35 assert.Equal(t, "hubot", response.Viewer.Login) 36 37 req := http.Requests[0] 38 reqBody, _ := ioutil.ReadAll(req.Body) 39 assert.Equal(t, `{"query":"QUERY","variables":{"name":"Mona"}}`, string(reqBody)) 40 assert.Equal(t, "token OTOKEN", req.Header.Get("Authorization")) 41 } 42 43 func TestGraphQLError(t *testing.T) { 44 http := &httpmock.Registry{} 45 client := NewClient(ReplaceTripper(http)) 46 47 response := struct{}{} 48 49 http.Register( 50 httpmock.GraphQL(""), 51 httpmock.StringResponse(` 52 { "errors": [ 53 {"message":"OH NO"}, 54 {"message":"this is fine"} 55 ] 56 } 57 `), 58 ) 59 60 err := client.GraphQL("github.com", "", nil, &response) 61 if err == nil || err.Error() != "GraphQL error: OH NO\nthis is fine" { 62 t.Fatalf("got %q", err.Error()) 63 } 64 } 65 66 func TestRESTGetDelete(t *testing.T) { 67 http := &httpmock.Registry{} 68 69 client := NewClient( 70 ReplaceTripper(http), 71 ) 72 73 http.Register( 74 httpmock.REST("DELETE", "applications/CLIENTID/grant"), 75 httpmock.StatusStringResponse(204, "{}"), 76 ) 77 78 r := bytes.NewReader([]byte(`{}`)) 79 err := client.REST("github.com", "DELETE", "applications/CLIENTID/grant", r, nil) 80 assert.NoError(t, err) 81 } 82 83 func TestRESTError(t *testing.T) { 84 fakehttp := &httpmock.Registry{} 85 client := NewClient(ReplaceTripper(fakehttp)) 86 87 fakehttp.Register(httpmock.MatchAny, func(req *http.Request) (*http.Response, error) { 88 return &http.Response{ 89 Request: req, 90 StatusCode: 422, 91 Body: ioutil.NopCloser(bytes.NewBufferString(`{"message": "OH NO"}`)), 92 Header: map[string][]string{ 93 "Content-Type": {"application/json; charset=utf-8"}, 94 }, 95 }, nil 96 }) 97 98 var httpErr HTTPError 99 err := client.REST("github.com", "DELETE", "repos/branch", nil, nil) 100 if err == nil || !errors.As(err, &httpErr) { 101 t.Fatalf("got %v", err) 102 } 103 104 if httpErr.StatusCode != 422 { 105 t.Errorf("expected status code 422, got %d", httpErr.StatusCode) 106 } 107 if httpErr.Error() != "HTTP 422: OH NO (https://api.github.com/repos/branch)" { 108 t.Errorf("got %q", httpErr.Error()) 109 110 } 111 }