-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
database_test.go
535 lines (489 loc) · 17.8 KB
/
database_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
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package database
import (
"context"
"fmt"
"log"
"net"
"strings"
"testing"
"time"
longrunning "cloud.google.com/go/longrunning/autogen"
"cloud.google.com/go/longrunning/autogen/longrunningpb"
"google.golang.org/api/option"
"google.golang.org/genproto/googleapis/spanner/admin/database/v1"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/metadata"
gstatus "google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
"google.golang.org/protobuf/types/known/anypb"
)
func Test_extractDBName(t *testing.T) {
g, w := extractDBName("CREATE DATABASE FOO"), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName(" CREATE DATABASE FOO"), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName(" CREATE\nDATABASE\tFOO"), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName(" CREATE DATABASE FOO "), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName("CREATE DATABASE `FOO`"), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName(" CREATE DATABASE `FOO` "), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName("CREATE DATABASE ```FOO```"), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
g, w = extractDBName(" CREATE DATABASE ```FOO``` "), "FOO"
if g != w {
t.Errorf("database name mismatch\nGot: %q\nWant: %q\n", g, w)
}
}
func (s *mockDatabaseAdminServer) ListDatabaseOperations(ctx context.Context, req *database.ListDatabaseOperationsRequest) (*database.ListDatabaseOperationsResponse, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
resp := s.resps[0]
s.resps = s.resps[1:]
return resp.(*database.ListDatabaseOperationsResponse), nil
}
var (
operationsClientOpt option.ClientOption
mockOperations mockOperationsServer
)
type mockOperationsServer struct {
// Embed for forward compatibility.
// Tests will keep working if more methods are added
// in the future.
longrunningpb.OperationsServer
reqs []proto.Message
// If set, all calls return this error.
err error
// responses to return if err == nil
resps []proto.Message
}
// initMockOperations initializes a separate long-running operations server
// that can be used for testing calls that need to list operations. The client
// needs to be manually linked with this server instead of the
// mockDatabaseAdmin server.
func initMockOperations() {
if operationsClientOpt != nil {
return
}
serv := grpc.NewServer()
longrunningpb.RegisterOperationsServer(serv, &mockOperations)
lis, err := net.Listen("tcp", "localhost:0")
if err != nil {
log.Fatal(err)
}
go serv.Serve(lis)
conn, err := grpc.Dial(lis.Addr().String(), grpc.WithInsecure())
if err != nil {
log.Fatal(err)
}
operationsClientOpt = option.WithGRPCConn(conn)
}
func (s *mockOperationsServer) GetOperation(ctx context.Context, req *longrunningpb.GetOperationRequest) (*longrunningpb.Operation, error) {
md, _ := metadata.FromIncomingContext(ctx)
if xg := md["x-goog-api-client"]; len(xg) == 0 || !strings.Contains(xg[0], "gl-go/") {
return nil, fmt.Errorf("x-goog-api-client = %v, expected gl-go key", xg)
}
s.reqs = append(s.reqs, req)
if s.err != nil {
return nil, s.err
}
resp := s.resps[0]
s.resps = s.resps[1:]
return resp.(*longrunningpb.Operation), nil
}
func Test_CreateDatabaseWithRetry(t *testing.T) {
var name string = "name3373707"
var expectedResponse = &database.Database{
Name: name,
}
mockDatabaseAdmin.err = nil
mockDatabaseAdmin.reqs = nil
any, err := anypb.New(expectedResponse)
if err != nil {
t.Fatal(err)
}
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps[:0], &longrunningpb.Operation{
Name: "longrunning-test",
Done: true,
Result: &longrunningpb.Operation_Response{Response: any},
})
var formattedParent string = fmt.Sprintf("projects/%s/instances/%s", "[PROJECT]", "[INSTANCE]")
var createStatement string = fmt.Sprintf("CREATE DATABASE %s", name)
var request = &database.CreateDatabaseRequest{
Parent: formattedParent,
CreateStatement: createStatement,
}
c, err := NewDatabaseAdminClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
respLRO, err := c.CreateDatabaseWithRetry(context.Background(), request)
if err != nil {
t.Fatal(err)
}
resp, err := respLRO.Wait(context.Background())
if err != nil {
t.Fatal(err)
}
if want, got := request, mockDatabaseAdmin.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
if want, got := expectedResponse, resp; !proto.Equal(want, got) {
t.Errorf("wrong response %q, want %q)", got, want)
}
}
type testRetryer struct {
f func(err error) (pause time.Duration, shouldRetry bool)
}
func (r *testRetryer) Retry(err error) (pause time.Duration, shouldRetry bool) {
return r.f(err)
}
func Test_CreateDatabaseWithRetry_Unavailable_ServerReceivedRequest_OperationInProgress(t *testing.T) {
// Initialize a mock operations server as we will need to list long-running
// operations.
initMockOperations()
// Use a specific test retry that will ensure that consecutive calls to the
// mock server will return different answers.
originalRetryer := retryer
defer func() { retryer = originalRetryer }()
// Set up mockDatabaseAdmin to return an Unavailable error for
// CreateDatabase.
var name string = "name3373707"
errs := []error{gstatus.Error(codes.Unavailable, "test error")}
mockDatabaseAdmin.err = errs[0]
retryer = &testRetryer{f: func(err error) (pause time.Duration, shouldRetry bool) {
code := gstatus.Code(err)
if code == codes.Unavailable || code == codes.DeadlineExceeded {
// Pop the errors from the stack to prevent the same error from
// being returned each time.
if len(errs) > 1 {
mockDatabaseAdmin.err = errs[0]
errs = errs[1:]
} else {
mockDatabaseAdmin.err = nil
}
return time.Millisecond, true
}
return 0, false
}}
// Set up the mockDatabaseAdmin to return a long-running operation for the
// initial CreateDatabase call.
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps[:0], &database.ListDatabaseOperationsResponse{
Operations: []*longrunningpb.Operation{
{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
Done: false,
},
},
NextPageToken: "",
})
// Setup the mockOperations to first return an operation that is not yet
// done, and then an operation that is done with the expected database.
mockOperations.resps = append(mockOperations.resps, &longrunningpb.Operation{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
Done: false,
})
var expectedResponse = &database.Database{
Name: name,
}
any, err := anypb.New(expectedResponse)
if err != nil {
t.Fatal(err)
}
mockOperations.resps = append(mockOperations.resps, &longrunningpb.Operation{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
Done: true,
Result: &longrunningpb.Operation_Response{Response: any},
})
mockDatabaseAdmin.reqs = nil
var formattedParent string = fmt.Sprintf("projects/%s/instances/%s", "[PROJECT]", "[INSTANCE]")
var createStatement string = fmt.Sprintf("CREATE DATABASE %s", name)
var request = &database.CreateDatabaseRequest{
Parent: formattedParent,
CreateStatement: createStatement,
}
c, err := NewDatabaseAdminClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
// Set the operations client manually.
c.LROClient, err = longrunning.NewOperationsClient(context.Background(), operationsClientOpt)
if err != nil {
t.Fatal(err)
}
respLRO, err := c.CreateDatabaseWithRetry(context.Background(), request)
if err != nil {
t.Fatal(err)
}
resp, err := respLRO.Wait(context.Background())
if err != nil {
t.Fatal(err)
}
// The requests should be:
// 1. CreateDatabase
// 2. ListDatabaseOperations
// 3. GetOperation (poll, done=False)
// 4. GetOperation (poll, done=True)
if want, got := request, mockDatabaseAdmin.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
listReq := &database.ListDatabaseOperationsRequest{
Parent: "projects/[PROJECT]/instances/[INSTANCE]",
Filter: fmt.Sprintf("(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata) AND (name:projects/[PROJECT]/instances/[INSTANCE]/databases/%s/operations/)", name),
}
if want, got := listReq, mockDatabaseAdmin.reqs[1]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
getReq := &longrunningpb.GetOperationRequest{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
}
if want, got := getReq, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
if want, got := getReq, mockOperations.reqs[1]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
// The end result for the user should just be the database.
if want, got := expectedResponse, resp; !proto.Equal(want, got) {
t.Errorf("request mismatch:\nGot: %q\nWant: %q)", got, want)
}
}
func Test_CreateDatabaseWithRetry_Unavailable_ServerReceivedRequest_OperationFinished(t *testing.T) {
// Initialize a mock operations server as we will need to list long-running
// operations.
initMockOperations()
// Use a specific test retry that will ensure that consecutive calls to the
// mock server will return different answers.
originalRetryer := retryer
defer func() { retryer = originalRetryer }()
// Set up mockDatabaseAdmin to return an Unavailable error for
// CreateDatabase.
var name string = "name3373707"
errs := []error{gstatus.Error(codes.Unavailable, "test error")}
mockDatabaseAdmin.err = errs[0]
retryer = &testRetryer{f: func(err error) (pause time.Duration, shouldRetry bool) {
code := gstatus.Code(err)
if code == codes.Unavailable || code == codes.DeadlineExceeded {
// Pop the errors from the stack to prevent the same error from
// being returned each time.
if len(errs) > 1 {
mockDatabaseAdmin.err = errs[0]
errs = errs[1:]
} else {
mockDatabaseAdmin.err = nil
}
return time.Millisecond, true
}
return 0, false
}}
var expectedResponse = &database.Database{
Name: name,
}
any, err := anypb.New(expectedResponse)
if err != nil {
t.Fatal(err)
}
// Set up the mockDatabaseAdmin to return a long-running operation that was
// created by the initial CreateDatabase call.
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps[:0], &database.ListDatabaseOperationsResponse{
Operations: []*longrunningpb.Operation{
{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
Done: true,
Result: &longrunningpb.Operation_Response{Response: any},
},
},
NextPageToken: "",
})
// Append the actual database as the next response for the GetDatabase call.
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps, expectedResponse)
// Append a long-running operation that will return the database.
mockOperations.resps = append(mockOperations.resps, &longrunningpb.Operation{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
Done: true,
Result: &longrunningpb.Operation_Response{Response: any},
})
mockDatabaseAdmin.reqs = nil
var formattedParent string = fmt.Sprintf("projects/%s/instances/%s", "[PROJECT]", "[INSTANCE]")
var createStatement string = fmt.Sprintf("CREATE DATABASE %s", name)
var request = &database.CreateDatabaseRequest{
Parent: formattedParent,
CreateStatement: createStatement,
}
c, err := NewDatabaseAdminClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
// Set the operations client manually.
c.LROClient, err = longrunning.NewOperationsClient(context.Background(), operationsClientOpt)
if err != nil {
t.Fatal(err)
}
respLRO, err := c.CreateDatabaseWithRetry(context.Background(), request)
if err != nil {
t.Fatal(err)
}
resp, err := respLRO.Wait(context.Background())
if err != nil {
t.Fatal(err)
}
// The requests should be:
// 1. CreateDatabase
// 2. ListDatabaseOperations
// 3. GetDatabase
// 4. GetOperation (poll, done=True)
if want, got := request, mockDatabaseAdmin.reqs[0]; !proto.Equal(want, got) {
t.Errorf("wrong request %q, want %q", got, want)
}
listReq := &database.ListDatabaseOperationsRequest{
Parent: "projects/[PROJECT]/instances/[INSTANCE]",
Filter: fmt.Sprintf("(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata) AND (name:projects/[PROJECT]/instances/[INSTANCE]/databases/%s/operations/)", name),
}
if want, got := listReq, mockDatabaseAdmin.reqs[1]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
getDbReq := &database.GetDatabaseRequest{
Name: fmt.Sprintf("projects/[PROJECT]/instances/[INSTANCE]/databases/%s", name),
}
if want, got := getDbReq, mockDatabaseAdmin.reqs[2]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
getReq := &longrunningpb.GetOperationRequest{
Name: fmt.Sprintf("projects/p/instances/i/databases/%s/operations/1", name),
}
if want, got := getReq, mockOperations.reqs[0]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
// The end result for the user should just be the database.
if want, got := expectedResponse, resp; !proto.Equal(want, got) {
t.Errorf("request mismatch:\nGot: %q\nWant: %q)", got, want)
}
}
func Test_CreateDatabaseWithRetry_Unavailable_ServerDidNotReceiveRequest(t *testing.T) {
// Initialize a mock operations server as we will need to list long-running
// operations.
initMockOperations()
// Use a specific test retry that will ensure that consecutive calls to the
// mock server will return different answers.
originalRetryer := retryer
defer func() { retryer = originalRetryer }()
var name string = "name3373707"
var expectedResponse = &database.Database{
Name: name,
}
any, err := anypb.New(expectedResponse)
if err != nil {
t.Fatal(err)
}
// Set up mockDatabaseAdmin to return an Unavailable error for
// CreateDatabase.
errs := []error{gstatus.Error(codes.Unavailable, "test error")}
mockDatabaseAdmin.err = errs[0]
retryer = &testRetryer{f: func(err error) (pause time.Duration, shouldRetry bool) {
code := gstatus.Code(err)
if code == codes.Unavailable || code == codes.DeadlineExceeded {
// Pop the errors from the stack to prevent the same error from
// being returned each time.
if len(errs) > 1 {
mockDatabaseAdmin.err = errs[0]
errs = errs[1:]
} else {
mockDatabaseAdmin.err = nil
}
return time.Millisecond, true
}
return 0, false
}}
// Set up the mockDatabaseAdmin to return an empty list of operations.
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps[:0], &database.ListDatabaseOperationsResponse{
Operations: []*longrunningpb.Operation{},
NextPageToken: "",
})
// The next call should succeed directly.
mockDatabaseAdmin.resps = append(mockDatabaseAdmin.resps, &longrunningpb.Operation{
Name: "longrunning-test",
Done: true,
Result: &longrunningpb.Operation_Response{Response: any},
})
mockDatabaseAdmin.reqs = nil
var formattedParent string = fmt.Sprintf("projects/%s/instances/%s", "[PROJECT]", "[INSTANCE]")
var createStatement string = fmt.Sprintf("CREATE DATABASE %s", name)
var request = &database.CreateDatabaseRequest{
Parent: formattedParent,
CreateStatement: createStatement,
}
c, err := NewDatabaseAdminClient(context.Background(), clientOpt)
if err != nil {
t.Fatal(err)
}
// Set the operations client manually.
c.LROClient, err = longrunning.NewOperationsClient(context.Background(), operationsClientOpt)
if err != nil {
t.Fatal(err)
}
respLRO, err := c.CreateDatabaseWithRetry(context.Background(), request)
if err != nil {
t.Fatal(err)
}
resp, err := respLRO.Wait(context.Background())
if err != nil {
t.Fatal(err)
}
// The requests should be:
// 1. CreateDatabase
// 2. ListDatabaseOperations
// 3. CreateDatabase
if want, got := request, mockDatabaseAdmin.reqs[0]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
listReq := &database.ListDatabaseOperationsRequest{
Parent: "projects/[PROJECT]/instances/[INSTANCE]",
Filter: fmt.Sprintf("(metadata.@type:type.googleapis.com/google.spanner.admin.database.v1.CreateDatabaseMetadata) AND (name:projects/[PROJECT]/instances/[INSTANCE]/databases/%s/operations/)", name),
}
if want, got := listReq, mockDatabaseAdmin.reqs[1]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
if want, got := request, mockDatabaseAdmin.reqs[2]; !proto.Equal(want, got) {
t.Errorf("request mismatch\nGot: %q\nWant %q\n", got, want)
}
// The end result for the user should just be the database.
if want, got := expectedResponse, resp; !proto.Equal(want, got) {
t.Errorf("request mismatch:\nGot: %q\nWant: %q)", got, want)
}
}