-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp_test.go
282 lines (256 loc) · 8.2 KB
/
http_test.go
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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
package http
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"reflect"
"testing"
"time"
)
func Test_NewClient(t *testing.T) {
client := NewClient("http://localhost:4001", nil)
if client == nil {
t.Error("Expected client to be non-nil")
}
if err := client.Close(); err != nil {
t.Errorf("Expected nil error, got %v", err)
}
}
func Test_BasicAuth(t *testing.T) {
username := "user"
password := "pass"
authExp := false
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/status" {
t.Fatalf("Unexpected path: %s", r.URL.Path)
}
user, pass, ok := r.BasicAuth()
if !authExp {
if ok {
t.Fatalf("basic auth should not be set")
}
return
}
if !ok {
t.Fatalf("Expected BasicAuth to be set")
}
if exp, got := username, user; exp != got {
t.Fatalf("Expected user to be '%s', got %s", exp, got)
}
if exp, got := password, pass; exp != got {
t.Fatalf("Expected pass to be '%s', got %s", exp, got)
}
}))
client := NewClient(ts.URL, nil)
if err := client.Status(context.Background()); err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
client.SetBasicAuth(username, password)
authExp = true
if err := client.Status(context.Background()); err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
client.SetBasicAuth("", "")
authExp = false
if err := client.Status(context.Background()); err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
if err := client.Close(); err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
}
func Test_Execute(t *testing.T) {
for _, tt := range []struct {
name string
statements SQLStatements
opts *ExecuteOptions
expURLValues url.Values
respBody string
}{
{
name: "single CREATE TABLE statement",
statements: NewSQLStatementsFromStrings([]string{"CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)"}),
opts: nil,
respBody: `{"results": [{"last_insert_id": 123, "rows_affected": 456}]}`,
},
{
name: "single CREATE TABLE statement with options",
statements: NewSQLStatementsFromStrings([]string{"CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)"}),
opts: &ExecuteOptions{Transaction: true, Timeout: mustParseDuration("1s")},
respBody: `{"results": [{"last_insert_id": 123, "rows_affected": 456}]}`,
expURLValues: url.Values{"transaction": []string{"true"}, "timeout": []string{"1s"}},
},
{
name: "two CREATE TABLE statements",
statements: NewSQLStatementsFromStrings([]string{"CREATE TABLE foo (id INTEGER PRIMARY KEY, name TEXT)", "CREATE TABLE bar (id INTEGER PRIMARY KEY, name TEXT)"}),
opts: nil,
respBody: `{"results": [{"last_insert_id": 123, "rows_affected": 456}, {"last_insert_id": 789, "rows_affected": 101112}]}`,
},
{
name: "single INSERT statement with positional arguments",
statements: SQLStatements{SQLStatement{SQL: "INSERT INTO foo VALUES(?, ?)", PositionalParams: []any{"name", float64(123)}}},
opts: nil,
respBody: `{"results": [{"last_insert_id": 123, "rows_affected": 456}]}`,
expURLValues: nil,
},
{
name: "single INSERT statement with named arguments",
statements: SQLStatements{SQLStatement{SQL: "INSERT INTO foo VALUES(:name, :age)", NamedParams: map[string]any{"name": "name", "age": float64(123)}}},
opts: nil,
respBody: `{"results": [{"last_insert_id": 123, "rows_affected": 456}]}`,
expURLValues: nil,
},
} {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/db/execute" {
t.Fatalf("Unexpected path: %s", r.URL.Path)
}
if r.Method != http.MethodPost {
t.Fatalf("Expected POST, got %s", r.Method)
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("Unexpected error reading body: %v", err)
}
defer r.Body.Close()
var gotStmts SQLStatements
if err := json.Unmarshal(body, &gotStmts); err != nil {
t.Fatalf("Unexpected error unmarshalling body: %v", err)
}
if !reflect.DeepEqual(tt.statements, gotStmts) {
t.Fatalf("Expected '%v' in request body, got '%v'", tt.statements, gotStmts)
}
if tt.expURLValues != nil {
values, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
t.Fatalf("Unexpected error parsing query string: %s", r.URL.RawQuery)
}
if !reflect.DeepEqual(tt.expURLValues, values) {
t.Fatalf("Expected %v, got %v", tt.expURLValues, r.URL.Query())
}
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(tt.respBody))
}))
defer ts.Close()
client := NewClient(ts.URL, nil)
defer client.Close()
gotER, err := client.Execute(context.Background(), tt.statements, tt.opts)
if err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
expER := mustUnmarshalExecuteResponse(tt.respBody)
if reflect.DeepEqual(expER, gotER) {
t.Fatalf("Expected %+v, got %+v", expER, gotER)
}
})
}
}
func Test_Query(t *testing.T) {
tests := []struct {
name string
statements SQLStatements
opts QueryOptions
expURLValues url.Values
respBody string
}{
{
name: "simple SELECT query",
statements: NewSQLStatementsFromStrings([]string{"SELECT * FROM foo"}),
opts: QueryOptions{},
expURLValues: nil,
respBody: `{"results": [{"columns": ["id", "name"], "values": [[1, "Alice"], [2, "Bob"]]}], "time": 0.456}`,
},
{
name: "SELECT query with options",
statements: NewSQLStatementsFromStrings([]string{"SELECT name FROM bar"}),
opts: QueryOptions{
Pretty: true,
Timeout: mustParseDuration("2s"),
},
expURLValues: url.Values{
"pretty": []string{"true"},
"timeout": []string{"2s"},
},
respBody: `{"results": [{"columns": ["name"], "values": [["Charlie"]]}], "time": 0.789}`,
},
{
name: "multiple SELECT queries",
statements: NewSQLStatementsFromStrings([]string{"SELECT 1", "SELECT 2"}),
opts: QueryOptions{},
expURLValues: nil,
respBody: `{"results": [{"columns": ["?column?"], "values": [[1]]}, {"columns": ["?column?"], "values": [[2]]}], "time": 1.234}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/db/query" {
t.Fatalf("Unexpected path: %s", r.URL.Path)
}
if r.Method != http.MethodPost {
t.Fatalf("Expected POST, got %s", r.Method)
}
body, err := io.ReadAll(r.Body)
if err != nil {
t.Fatalf("Unexpected error reading body: %v", err)
}
defer r.Body.Close()
var gotStmts SQLStatements
if err := json.Unmarshal(body, &gotStmts); err != nil {
t.Fatalf("Unexpected error unmarshalling body: %v", err)
}
if !reflect.DeepEqual(tt.statements, gotStmts) {
t.Fatalf("Expected statements %+v, got %+v", tt.statements, gotStmts)
}
if tt.expURLValues != nil {
values, err := url.ParseQuery(r.URL.RawQuery)
if err != nil {
t.Fatalf("Unexpected error parsing query string: %s", r.URL.RawQuery)
}
if !reflect.DeepEqual(tt.expURLValues, values) {
t.Fatalf("Expected URL values %v, got %v", tt.expURLValues, values)
}
}
w.WriteHeader(http.StatusOK)
w.Write([]byte(tt.respBody))
}))
defer ts.Close()
client := NewClient(ts.URL, nil)
defer client.Close()
gotQR, err := client.Query(context.Background(), tt.statements, tt.opts)
if err != nil {
t.Fatalf("Expected nil error, got %v", err)
}
expQR := mustUnmarshalQueryResponse(tt.respBody)
if !reflect.DeepEqual(expQR, *gotQR) {
t.Fatalf("Expected %+v, got %+v", expQR, gotQR)
}
})
}
}
func mustUnmarshalQueryResponse(s string) QueryResponse {
var qr QueryResponse
if err := json.Unmarshal([]byte(s), &qr); err != nil {
panic(err)
}
return qr
}
func mustUnmarshalExecuteResponse(s string) ExecuteResponse {
var er ExecuteResponse
if err := json.Unmarshal([]byte(s), &er); err != nil {
panic(err)
}
return er
}
func mustParseDuration(s string) time.Duration {
d, err := time.ParseDuration(s)
if err != nil {
panic(err)
}
return d
}