From 6a5532481f2a11d7dcd75d09c1fb67541ae7a587 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mislav=20Marohni=C4=87?= Date: Thu, 22 Dec 2022 21:45:17 +0100 Subject: [PATCH] Avoid sending empty JSON body when no params to api command (#6775) --- pkg/cmd/api/api.go | 5 ++++- pkg/cmd/api/api_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/pkg/cmd/api/api.go b/pkg/cmd/api/api.go index ac2321393..00e610dcd 100644 --- a/pkg/cmd/api/api.go +++ b/pkg/cmd/api/api.go @@ -246,7 +246,10 @@ func apiRun(opts *ApiOptions) error { } method := opts.RequestMethod requestHeaders := opts.RequestHeaders - var requestBody interface{} = params + var requestBody interface{} + if len(params) > 0 { + requestBody = params + } if !opts.RequestMethodPassed && (len(params) > 0 || opts.RequestInputFile != "") { method = "POST" diff --git a/pkg/cmd/api/api_test.go b/pkg/cmd/api/api_test.go index a822e5c06..b9cd2777f 100644 --- a/pkg/cmd/api/api_test.go +++ b/pkg/cmd/api/api_test.go @@ -671,6 +671,7 @@ func Test_apiRun_paginationGraphQL(t *testing.T) { return config.NewBlankConfig(), nil }, + RawFields: []string{"foo=bar"}, RequestMethod: "POST", RequestPath: "graphql", Paginate: true, @@ -764,6 +765,7 @@ func Test_apiRun_paginated_template(t *testing.T) { RequestMethod: "POST", RequestPath: "graphql", + RawFields: []string{"foo=bar"}, Paginate: true, // test that templates executed per page properly render a table. Template: `{{range .data.nodes}}{{tablerow .page .caption}}{{end}}`, @@ -798,6 +800,36 @@ func Test_apiRun_paginated_template(t *testing.T) { assert.Equal(t, "PAGE1_END", endCursor) } +func Test_apiRun_DELETE(t *testing.T) { + ios, _, _, _ := iostreams.Test() + + var gotRequest *http.Request + err := apiRun(&ApiOptions{ + IO: ios, + Config: func() (config.Config, error) { + return config.NewBlankConfig(), nil + }, + HttpClient: func() (*http.Client, error) { + var tr roundTripper = func(req *http.Request) (*http.Response, error) { + gotRequest = req + return &http.Response{StatusCode: 204, Request: req}, nil + } + return &http.Client{Transport: tr}, nil + }, + MagicFields: []string(nil), + RawFields: []string(nil), + RequestMethod: "DELETE", + RequestMethodPassed: true, + }) + if err != nil { + t.Fatalf("got error %v", err) + } + + if gotRequest.Body != nil { + t.Errorf("expected nil request body, got %T", gotRequest.Body) + } +} + func Test_apiRun_inputFile(t *testing.T) { tests := []struct { name string