Skip to content

Commit

Permalink
udpates after review:
Browse files Browse the repository at this point in the history
* rename "--postFile" to just "--file"
* add unit tests for "--file"
* reword help description
  • Loading branch information
arnej27959 committed Nov 13, 2024
1 parent 61f94d8 commit 1edbc89
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 10 deletions.
13 changes: 3 additions & 10 deletions client/go/internal/cli/cmd/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,7 @@ can be set by the syntax [parameter-name]=[value].`,
},
}
cmd.Flags().BoolVarP(&printCurl, "verbose", "v", false, "Print the equivalent curl command for the query")
cmd.Flags().StringVarP(&postFile, "postFile", "", "", "Use the given JSON file, POST to the query API")
cmd.Flags().StringVarP(&postFile, "file", "", "", "Read query parameters from the given JSON file and send a POST request, with overrides from arguments")
cmd.Flags().StringVarP(&format, "format", "", "human", "Output format. Must be 'human' (human-readable) or 'plain' (no formatting)")
cmd.Flags().StringSliceVarP(&headers, "header", "", nil, "Add a header to the HTTP request, on the format 'Header: Value'. This can be specified multiple times")
cmd.Flags().IntVarP(&queryTimeoutSecs, "timeout", "T", 10, "Timeout for the query in seconds")
Expand Down Expand Up @@ -84,10 +84,6 @@ func printCurl(stderr io.Writer, req *http.Request, postFile string, service *ve
return err
}

type nopCloser struct{ io.Reader }

func (nopCloser) Close() error { return nil }

func query(cli *CLI, arguments []string, timeoutSecs int, curl bool, format string, postFile string, headers []string, waiter *Waiter) error {
target, err := cli.target(targetOptions{})
if err != nil {
Expand All @@ -102,10 +98,7 @@ func query(cli *CLI, arguments []string, timeoutSecs int, curl bool, format stri
default:
return fmt.Errorf("invalid format: %s", format)
}
url, _ := url.Parse(service.BaseURL + "/search/")
if strings.HasSuffix(service.BaseURL, "/") {
url, _ = url.Parse(service.BaseURL + "search/")
}
url, _ := url.Parse(strings.TrimSuffix(service.BaseURL, "/") + "/search/")
urlQuery := url.Query()
for i := range len(arguments) {
key, value := splitArg(arguments[i])
Expand Down Expand Up @@ -133,7 +126,7 @@ func query(cli *CLI, arguments []string, timeoutSecs int, curl bool, format stri
}
header.Set("Content-Type", "application/json")
hReq.Method = "POST"
hReq.Body = nopCloser{bytes.NewBuffer(bytes.Clone(json))}
hReq.Body = io.NopCloser(bytes.NewBuffer(bytes.Clone(json)))
if err != nil {
return fmt.Errorf("bad postFile '%s': %w", postFile, err)
}
Expand Down
48 changes: 48 additions & 0 deletions client/go/internal/cli/cmd/query_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,13 @@ package cmd

import (
"net/http"
"os"
"path/filepath"
"strconv"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/vespa-engine/vespa/client/go/internal/mock"
)

Expand Down Expand Up @@ -134,6 +137,51 @@ data: {
assertStreamingQuery(t, bodyWithError, bodyWithError, "--format=plain")
}

func TestQueryPostFile(t *testing.T) {
mockResponse := `{"query":"result"}"`
client := &mock.HTTPClient{ReadBody: true}
client.NextResponseString(200, mockResponse)
cli, stdout, _ := newTestCLI(t)
cli.httpClient = client

tmpFileName := filepath.Join(t.TempDir(), "tq1.json")
jsonQuery := []byte(`{"yql": "some yql here"}`)
require.Nil(t, os.WriteFile(tmpFileName, jsonQuery, 0644))

assert.Nil(t, cli.Run("-t", "http://127.0.0.1:8080", "query", "--file", tmpFileName))
assert.Equal(t, mockResponse+"\n", stdout.String())
assert.Equal(t, `{"timeout":"10s","yql":"some yql here"}`, string(client.LastBody))
assert.Equal(t, []string{"application/json"}, client.LastRequest.Header.Values("Content-Type"))
assert.Equal(t, "POST", client.LastRequest.Method)
assert.Equal(t, "http://127.0.0.1:8080/search/", client.LastRequest.URL.String())
}

func TestQueryPostFileWithArgs(t *testing.T) {
mockResponse := `{"query":"result"}"`
client := &mock.HTTPClient{ReadBody: true}
client.NextResponseString(200, mockResponse)
cli, _, _ := newTestCLI(t)
cli.httpClient = client

tmpFileName := filepath.Join(t.TempDir(), "tq2.json")
jsonQuery := []byte(`{"yql": "some yql here"}`)
require.Nil(t, os.WriteFile(tmpFileName, jsonQuery, 0644))

assert.Nil(t, cli.Run(
"-t", "http://foo.bar:1234/",
"query",
"--file", tmpFileName,
"yql=foo bar",
"tracelevel=3",
"dispatch.docsumRetryLimit=42"))
assert.Equal(t,
`{"dispatch.docsumRetryLimit":"42","timeout":"10s","tracelevel":"3","yql":"foo bar"}`,
string(client.LastBody))
assert.Equal(t, []string{"application/json"}, client.LastRequest.Header.Values("Content-Type"))
assert.Equal(t, "POST", client.LastRequest.Method)
assert.Equal(t, "http://foo.bar:1234/search/", client.LastRequest.URL.String())
}

func assertStreamingQuery(t *testing.T, expectedOutput, body string, args ...string) {
t.Helper()
client := &mock.HTTPClient{}
Expand Down

0 comments on commit 1edbc89

Please sign in to comment.