aboutsummaryrefslogtreecommitdiffstats
path: root/client/go/internal/cli/cmd/query_test.go
blob: f5b113b6acb7483b5836118bfacd0c78a4b7a89f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
// query command tests
// Author: bratseth

package cmd

import (
	"net/http"
	"strconv"
	"testing"

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

func TestQuery(t *testing.T) {
	assertQuery(t,
		"?timeout=10s&yql=select+from+sources+%2A+where+title+contains+%27foo%27",
		"select from sources * where title contains 'foo'")
}

func TestQueryVerbose(t *testing.T) {
	client := &mock.HTTPClient{}
	client.NextResponseString(200, "{\"query\":\"result\"}")

	cli, stdout, stderr := newTestCLI(t)
	cli.httpClient = client

	assert.Nil(t, cli.Run("-t", "http://127.0.0.1:8080", "query", "-v", "select from sources * where title contains 'foo'"))
	assert.Equal(t, "curl 'http://127.0.0.1:8080/search/?timeout=10s&yql=select+from+sources+%2A+where+title+contains+%27foo%27'\n", stderr.String())
	assert.Equal(t, "{\n    \"query\": \"result\"\n}\n", stdout.String())
}

func TestQueryUnformatted(t *testing.T) {
	client := &mock.HTTPClient{}
	client.NextResponseString(200, "{\"query\":\"result\"}")
	cli, stdout, _ := newTestCLI(t)
	cli.httpClient = client

	assert.Nil(t, cli.Run("-t", "http://127.0.0.1:8080", "--format=plain", "query", "select from sources * where title contains 'foo'"))
	assert.Equal(t, "{\"query\":\"result\"}\n", stdout.String())
}

func TestQueryNonJsonResult(t *testing.T) {
	assertQuery(t,
		"?timeout=10s&yql=select+from+sources+%2A+where+title+contains+%27foo%27",
		"select from sources * where title contains 'foo'")
}

func TestQueryWithMultipleParameters(t *testing.T) {
	assertQuery(t,
		"?hits=5&timeout=20s&yql=select+from+sources+%2A+where+title+contains+%27foo%27+and+year+%3D+2000",
		"select from sources * where title contains 'foo' and year = 2000", "hits=5", "timeout=20s")
}

func TestQueryWithEquals(t *testing.T) {
	assertQuery(t,
		"?timeout=10s&yql=SELECT+from+sources+%2A+where+title+contains+%27foo%27+and+year+%3D+2000",
		"SELECT from sources * where title contains 'foo' and year = 2000")
}

func TestQuerySelect(t *testing.T) {
	assertQuery(t,
		"?hits=5&select=%7B%22select%22%3A%7B%22where%22%3A%7B%22contains%22%3A%5B%22title%22%2C%22a%22%5D%7D%7D%7D&timeout=10s",
		`select={"select":{"where":{"contains":["title","a"]}}}`, "hits=5")
}

func TestQueryWithExplicitYqlParameter(t *testing.T) {
	assertQuery(t,
		"?timeout=10s&yql=select+from+sources+%2A+where+title+contains+%27foo%27",
		"yql=select from sources * where title contains 'foo'")
}

func TestIllegalQuery(t *testing.T) {
	assertQueryError(t, 401, "query error message")
}

func TestServerError(t *testing.T) {
	assertQueryServiceError(t, 501, "server error message")
}

func TestQueryHeader(t *testing.T) {
	client := &mock.HTTPClient{}
	client.NextResponseString(200, "{\"query\":\"result\"}")

	cli, _, stderr := newTestCLI(t)
	cli.httpClient = client

	assert.Nil(t, cli.Run("-t", "http://127.0.0.1:8080", "query",
		"--header", "X-Foo: bar",
		"--header", "X-Foo: baz",
		"--header", "X-Bar:   foo bar  ",
		"select from sources * where title contains 'foo'"))
	assert.Equal(t, []string{"bar", "baz"}, client.LastRequest.Header.Values("X-Foo"))
	assert.Equal(t, "foo bar", client.LastRequest.Header.Get("X-Bar"))

	assert.NotNil(t, cli.Run("-t", "http://127.0.0.1:8080", "query",
		"--header", "X-Foo", "select from sources * where title contains 'foo'"))
	assert.Equal(t, "Error: invalid header \"X-Foo\": missing colon separator\n", stderr.String())
}

func TestStreamingQuery(t *testing.T) {
	body := `
event: token
data: {"token": "The"}

event: token
data: {"token": " Manhattan"}

event: token
data: {"token": " Project"}

event: end
`
	assertStreamingQuery(t, "The Manhattan Project\n", body)
	assertStreamingQuery(t, body, body, "--format=plain")

	bodyWithError := `
event: token
data: {"token": "The"}

event: token
data:  Manhattan

event: error
data: {"message": "something went wrong"}
`
	assertStreamingQuery(t, `The Manhattan
event: error
data: {
    "message": "something went wrong"
}
`, bodyWithError)
	assertStreamingQuery(t, bodyWithError, bodyWithError, "--format=plain")
}

func assertStreamingQuery(t *testing.T, expectedOutput, body string, args ...string) {
	t.Helper()
	client := &mock.HTTPClient{}
	response := mock.HTTPResponse{Status: 200, Header: make(http.Header)}
	response.Header.Set("Content-Type", "text/event-stream")
	response.Body = []byte(body)
	client.NextResponse(response)
	cli, stdout, stderr := newTestCLI(t)
	cli.httpClient = client

	assert.Nil(t, cli.Run(append(args, "-t", "http://127.0.0.1:8080", "query", "select something")...))
	assert.Equal(t, "", stderr.String())
	assert.Equal(t, expectedOutput, stdout.String())
}

func assertStreamingQueryErr(t *testing.T, expectedOut, expectedErr, body string, args ...string) {
	t.Helper()
	client := &mock.HTTPClient{}
	response := mock.HTTPResponse{Status: 200, Header: make(http.Header)}
	response.Header.Set("Content-Type", "text/event-stream")
	response.Body = []byte(body)
	client.NextResponse(response)
	cli, stdout, stderr := newTestCLI(t)
	cli.httpClient = client

	assert.NotNil(t, cli.Run(append(args, "-t", "http://127.0.0.1:8080", "query", "select something")...))
	assert.Equal(t, expectedErr, stderr.String())
	assert.Equal(t, expectedOut, stdout.String())
}

func assertQuery(t *testing.T, expectedQuery string, query ...string) {
	client := &mock.HTTPClient{}
	client.NextResponseString(200, "{\"query\":\"result\"}")
	cli, stdout, _ := newTestCLI(t)
	cli.httpClient = client

	args := []string{"-t", "http://127.0.0.1:8080", "query"}
	assert.Nil(t, cli.Run(append(args, query...)...))
	assert.Equal(t,
		"{\n    \"query\": \"result\"\n}\n",
		stdout.String(),
		"query output")
	queryURL := "http://127.0.0.1:8080"
	assert.Equal(t, queryURL+"/search/"+expectedQuery, client.LastRequest.URL.String())
}

func assertQueryError(t *testing.T, status int, errorMessage string) {
	client := &mock.HTTPClient{}
	client.NextResponseString(status, errorMessage)
	cli, _, stderr := newTestCLI(t)
	cli.httpClient = client
	assert.NotNil(t, cli.Run("-t", "http://127.0.0.1:8080", "query", "yql=select from sources * where title contains 'foo'"))
	assert.Equal(t,
		"Error: invalid query: Status "+strconv.Itoa(status)+"\n"+errorMessage+"\n",
		stderr.String(),
		"error output")
}

func assertQueryServiceError(t *testing.T, status int, errorMessage string) {
	client := &mock.HTTPClient{}
	client.NextResponseString(status, errorMessage)
	cli, _, stderr := newTestCLI(t)
	cli.httpClient = client
	assert.NotNil(t, cli.Run("-t", "http://127.0.0.1:8080", "query", "yql=select from sources * where title contains 'foo'"))
	assert.Equal(t,
		"Error: Status "+strconv.Itoa(status)+" from container at 127.0.0.1:8080\n"+errorMessage+"\n",
		stderr.String(),
		"error output")
}