-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
integration_test.go
2846 lines (2600 loc) · 77.3 KB
/
integration_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
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 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
//
// http://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 bigquery
import (
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"log"
"math/big"
"net/http"
"os"
"sort"
"strings"
"testing"
"time"
"cloud.google.com/go/civil"
datacatalog "cloud.google.com/go/datacatalog/apiv1"
"cloud.google.com/go/httpreplay"
"cloud.google.com/go/internal"
"cloud.google.com/go/internal/pretty"
"cloud.google.com/go/internal/testutil"
"cloud.google.com/go/internal/uid"
"cloud.google.com/go/storage"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
gax "github.com/googleapis/gax-go/v2"
"google.golang.org/api/googleapi"
"google.golang.org/api/iterator"
"google.golang.org/api/option"
datacatalogpb "google.golang.org/genproto/googleapis/cloud/datacatalog/v1"
)
const replayFilename = "bigquery.replay"
var record = flag.Bool("record", false, "record RPCs")
var (
client *Client
storageClient *storage.Client
policyTagManagerClient *datacatalog.PolicyTagManagerClient
dataset *Dataset
otherDataset *Dataset
schema = Schema{
{Name: "name", Type: StringFieldType},
{Name: "nums", Type: IntegerFieldType, Repeated: true},
{Name: "rec", Type: RecordFieldType, Schema: Schema{
{Name: "bool", Type: BooleanFieldType},
}},
}
testTableExpiration time.Time
datasetIDs, tableIDs, modelIDs, routineIDs *uid.Space
)
// Note: integration tests cannot be run in parallel, because TestIntegration_Location
// modifies the client.
func TestMain(m *testing.M) {
cleanup := initIntegrationTest()
r := m.Run()
cleanup()
os.Exit(r)
}
func getClient(t *testing.T) *Client {
if client == nil {
t.Skip("Integration tests skipped")
}
return client
}
var grpcHeadersChecker = testutil.DefaultHeadersEnforcer()
// If integration tests will be run, create a unique dataset for them.
// Return a cleanup function.
func initIntegrationTest() func() {
ctx := context.Background()
flag.Parse() // needed for testing.Short()
projID := testutil.ProjID()
switch {
case testing.Short() && *record:
log.Fatal("cannot combine -short and -record")
return func() {}
case testing.Short() && httpreplay.Supported() && testutil.CanReplay(replayFilename) && projID != "":
// go test -short with a replay file will replay the integration tests if the
// environment variables are set.
log.Printf("replaying from %s", replayFilename)
httpreplay.DebugHeaders()
replayer, err := httpreplay.NewReplayer(replayFilename)
if err != nil {
log.Fatal(err)
}
var t time.Time
if err := json.Unmarshal(replayer.Initial(), &t); err != nil {
log.Fatal(err)
}
hc, err := replayer.Client(ctx) // no creds needed
if err != nil {
log.Fatal(err)
}
client, err = NewClient(ctx, projID, option.WithHTTPClient(hc))
if err != nil {
log.Fatal(err)
}
storageClient, err = storage.NewClient(ctx, option.WithHTTPClient(hc))
if err != nil {
log.Fatal(err)
}
policyTagManagerClient, err = datacatalog.NewPolicyTagManagerClient(ctx)
if err != nil {
log.Fatal(err)
}
cleanup := initTestState(client, t)
return func() {
cleanup()
_ = replayer.Close() // No actionable error returned.
}
case testing.Short():
// go test -short without a replay file skips the integration tests.
if testutil.CanReplay(replayFilename) && projID != "" {
log.Print("replay not supported for Go versions before 1.8")
}
client = nil
storageClient = nil
return func() {}
default: // Run integration tests against a real backend.
ts := testutil.TokenSource(ctx, Scope)
if ts == nil {
log.Println("Integration tests skipped. See CONTRIBUTING.md for details")
return func() {}
}
bqOpts := []option.ClientOption{option.WithTokenSource(ts)}
sOpts := []option.ClientOption{option.WithTokenSource(testutil.TokenSource(ctx, storage.ScopeFullControl))}
ptmOpts := []option.ClientOption{option.WithTokenSource(testutil.TokenSource(ctx, "https://www.googleapis.com/auth/cloud-platform"))}
cleanup := func() {}
now := time.Now().UTC()
if *record {
if !httpreplay.Supported() {
log.Print("record not supported for Go versions before 1.8")
} else {
nowBytes, err := json.Marshal(now)
if err != nil {
log.Fatal(err)
}
recorder, err := httpreplay.NewRecorder(replayFilename, nowBytes)
if err != nil {
log.Fatalf("could not record: %v", err)
}
log.Printf("recording to %s", replayFilename)
hc, err := recorder.Client(ctx, bqOpts...)
if err != nil {
log.Fatal(err)
}
bqOpts = append(bqOpts, option.WithHTTPClient(hc))
hc, err = recorder.Client(ctx, sOpts...)
if err != nil {
log.Fatal(err)
}
sOpts = append(sOpts, option.WithHTTPClient(hc))
cleanup = func() {
if err := recorder.Close(); err != nil {
log.Printf("saving recording: %v", err)
}
}
}
} else {
// When we're not recording, do http header checking.
// We can't check universally because option.WithHTTPClient is
// incompatible with gRPC options.
bqOpts = append(bqOpts, grpcHeadersChecker.CallOptions()...)
sOpts = append(sOpts, grpcHeadersChecker.CallOptions()...)
ptmOpts = append(ptmOpts, grpcHeadersChecker.CallOptions()...)
}
var err error
client, err = NewClient(ctx, projID, bqOpts...)
if err != nil {
log.Fatalf("NewClient: %v", err)
}
storageClient, err = storage.NewClient(ctx, sOpts...)
if err != nil {
log.Fatalf("storage.NewClient: %v", err)
}
policyTagManagerClient, err = datacatalog.NewPolicyTagManagerClient(ctx, ptmOpts...)
if err != nil {
log.Fatalf("datacatalog.NewPolicyTagManagerClient: %v", err)
}
c := initTestState(client, now)
return func() { c(); cleanup() }
}
}
func initTestState(client *Client, t time.Time) func() {
// BigQuery does not accept hyphens in dataset or table IDs, so we create IDs
// with underscores.
ctx := context.Background()
opts := &uid.Options{Sep: '_', Time: t}
datasetIDs = uid.NewSpace("dataset", opts)
tableIDs = uid.NewSpace("table", opts)
modelIDs = uid.NewSpace("model", opts)
routineIDs = uid.NewSpace("routine", opts)
testTableExpiration = t.Add(2 * time.Hour).Round(time.Second)
// For replayability, seed the random source with t.
Seed(t.UnixNano())
dataset = client.Dataset(datasetIDs.New())
otherDataset = client.Dataset(datasetIDs.New())
if err := dataset.Create(ctx, nil); err != nil {
log.Fatalf("creating dataset %s: %v", dataset.DatasetID, err)
}
if err := otherDataset.Create(ctx, nil); err != nil {
log.Fatalf("creating other dataset %s: %v", dataset.DatasetID, err)
}
return func() {
if err := dataset.DeleteWithContents(ctx); err != nil {
log.Printf("could not delete %s", dataset.DatasetID)
}
if err := otherDataset.DeleteWithContents(ctx); err != nil {
log.Printf("could not delete %s", dataset.DatasetID)
}
}
}
func TestIntegration_DetectProjectID(t *testing.T) {
ctx := context.Background()
testCreds := testutil.Credentials(ctx)
if testCreds == nil {
t.Skip("test credentials not present, skipping")
}
if _, err := NewClient(ctx, DetectProjectID, option.WithCredentials(testCreds)); err != nil {
t.Errorf("test NewClient: %v", err)
}
badTS := testutil.ErroringTokenSource{}
if badClient, err := NewClient(ctx, DetectProjectID, option.WithTokenSource(badTS)); err == nil {
t.Errorf("expected error from bad token source, NewClient succeeded with project: %s", badClient.Project())
}
}
func TestIntegration_JobFrom(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
// Create a job we can use for referencing.
q := client.Query("SELECT 123 as foo")
it, err := q.Read(ctx)
if err != nil {
t.Fatalf("failed to run test query: %v", err)
}
want := it.SourceJob()
// establish a new client that's pointed at an invalid project/location.
otherClient, err := NewClient(ctx, "bad-project-id")
if err != nil {
t.Fatalf("failed to create other client: %v", err)
}
otherClient.Location = "badloc"
for _, tc := range []struct {
description string
f func(*Client) (*Job, error)
wantErr bool
}{
{
description: "JobFromID",
f: func(c *Client) (*Job, error) { return c.JobFromID(ctx, want.jobID) },
wantErr: true,
},
{
description: "JobFromIDLocation",
f: func(c *Client) (*Job, error) { return c.JobFromIDLocation(ctx, want.jobID, want.location) },
wantErr: true,
},
{
description: "JobFromProject",
f: func(c *Client) (*Job, error) { return c.JobFromProject(ctx, want.projectID, want.jobID, want.location) },
},
} {
got, err := tc.f(otherClient)
if err != nil {
if !tc.wantErr {
t.Errorf("case %q errored: %v", tc.description, err)
}
continue
}
if tc.wantErr {
t.Errorf("case %q got success, expected error", tc.description)
}
if got.projectID != want.projectID {
t.Errorf("case %q projectID mismatch, got %s want %s", tc.description, got.projectID, want.projectID)
}
if got.location != want.location {
t.Errorf("case %q location mismatch, got %s want %s", tc.description, got.location, want.location)
}
if got.jobID != want.jobID {
t.Errorf("case %q jobID mismatch, got %s want %s", tc.description, got.jobID, want.jobID)
}
}
}
func TestIntegration_SnapshotRestoreClone(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
// instantiate a base table via a CTAS
baseTableID := tableIDs.New()
qualified := fmt.Sprintf("`%s`.%s.%s", testutil.ProjID(), dataset.DatasetID, baseTableID)
sql := fmt.Sprintf(`
CREATE TABLE %s
(
sample_value INT64,
groupid STRING,
)
AS
SELECT
CAST(RAND() * 100 AS INT64),
CONCAT("group", CAST(CAST(RAND()*10 AS INT64) AS STRING))
FROM
UNNEST(GENERATE_ARRAY(0,999))
`, qualified)
if _, _, err := runQuerySQL(ctx, sql); err != nil {
t.Fatalf("couldn't instantiate base table: %v", err)
}
// Create a snapshot. We'll select our snapshot time explicitly to validate the snapshot time is the same.
targetTime := time.Now()
snapshotID := tableIDs.New()
copier := dataset.Table(snapshotID).CopierFrom(dataset.Table(fmt.Sprintf("%s@%d", baseTableID, targetTime.UnixNano()/1e6)))
copier.OperationType = SnapshotOperation
job, err := copier.Run(ctx)
if err != nil {
t.Fatalf("couldn't run snapshot: %v", err)
}
err = wait(ctx, job)
if err != nil {
t.Fatalf("snapshot failed: %v", err)
}
// verify metadata on the snapshot
meta, err := dataset.Table(snapshotID).Metadata(ctx)
if err != nil {
t.Fatalf("couldn't get metadata from snapshot: %v", err)
}
if meta.Type != Snapshot {
t.Errorf("expected snapshot table type, got %s", meta.Type)
}
want := &SnapshotDefinition{
BaseTableReference: dataset.Table(baseTableID),
SnapshotTime: targetTime,
}
if diff := testutil.Diff(meta.SnapshotDefinition, want, cmp.AllowUnexported(Table{}), cmpopts.IgnoreUnexported(Client{}), cmpopts.EquateApproxTime(time.Millisecond)); diff != "" {
t.Fatalf("SnapshotDefinition differs. got=-, want=+:\n%s", diff)
}
// execute a restore using the snapshot.
restoreID := tableIDs.New()
restorer := dataset.Table(restoreID).CopierFrom(dataset.Table(snapshotID))
restorer.OperationType = RestoreOperation
job, err = restorer.Run(ctx)
if err != nil {
t.Fatalf("couldn't run restore: %v", err)
}
err = wait(ctx, job)
if err != nil {
t.Fatalf("restore failed: %v", err)
}
restoreMeta, err := dataset.Table(restoreID).Metadata(ctx)
if err != nil {
t.Fatalf("couldn't get restored table metadata: %v", err)
}
if meta.NumBytes != restoreMeta.NumBytes {
t.Errorf("bytes mismatch. snap had %d bytes, restore had %d bytes", meta.NumBytes, restoreMeta.NumBytes)
}
if meta.NumRows != restoreMeta.NumRows {
t.Errorf("row counts mismatch. snap had %d rows, restore had %d rows", meta.NumRows, restoreMeta.NumRows)
}
if restoreMeta.Type != RegularTable {
t.Errorf("table type mismatch, got %s want %s", restoreMeta.Type, RegularTable)
}
// Create a clone of the snapshot.
cloneID := tableIDs.New()
cloner := dataset.Table(cloneID).CopierFrom(dataset.Table(snapshotID))
cloner.OperationType = CloneOperation
job, err = cloner.Run(ctx)
if err != nil {
t.Fatalf("couldn't run clone: %v", err)
}
err = wait(ctx, job)
if err != nil {
t.Fatalf("clone failed: %v", err)
}
cloneMeta, err := dataset.Table(cloneID).Metadata(ctx)
if err != nil {
t.Fatalf("couldn't get restored table metadata: %v", err)
}
if meta.NumBytes != cloneMeta.NumBytes {
t.Errorf("bytes mismatch. snap had %d bytes, clone had %d bytes", meta.NumBytes, cloneMeta.NumBytes)
}
if meta.NumRows != cloneMeta.NumRows {
t.Errorf("row counts mismatch. snap had %d rows, clone had %d rows", meta.NumRows, cloneMeta.NumRows)
}
if cloneMeta.Type != RegularTable {
t.Errorf("table type mismatch, got %s want %s", cloneMeta.Type, RegularTable)
}
if cloneMeta.CloneDefinition == nil {
t.Errorf("expected CloneDefinition in (%q), was nil", cloneMeta.FullID)
}
if cloneMeta.CloneDefinition.BaseTableReference == nil {
t.Errorf("expected CloneDefinition.BaseTableReference, was nil")
}
wantBase := dataset.Table(snapshotID)
if !testutil.Equal(cloneMeta.CloneDefinition.BaseTableReference, wantBase, cmpopts.IgnoreUnexported(Table{})) {
t.Errorf("mismatch in CloneDefinition.BaseTableReference. Got %s, want %s", cloneMeta.CloneDefinition.BaseTableReference.FullyQualifiedName(), wantBase.FullyQualifiedName())
}
}
func TestIntegration_HourTimePartitioning(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
table := dataset.Table(tableIDs.New())
schema := Schema{
{Name: "name", Type: StringFieldType},
{Name: "somevalue", Type: IntegerFieldType},
}
// define hourly ingestion-based partitioning.
wantedTimePartitioning := &TimePartitioning{
Type: HourPartitioningType,
}
err := table.Create(context.Background(), &TableMetadata{
Schema: schema,
TimePartitioning: wantedTimePartitioning,
})
if err != nil {
t.Fatal(err)
}
defer table.Delete(ctx)
md, err := table.Metadata(ctx)
if err != nil {
t.Fatal(err)
}
if md.TimePartitioning == nil {
t.Fatal("expected time partitioning, got nil")
}
if diff := testutil.Diff(md.TimePartitioning, wantedTimePartitioning); diff != "" {
t.Fatalf("got=-, want=+:\n%s", diff)
}
if md.TimePartitioning.Type != wantedTimePartitioning.Type {
t.Errorf("TimePartitioning interval mismatch: got %v, wanted %v", md.TimePartitioning.Type, wantedTimePartitioning.Type)
}
}
func TestIntegration_RangePartitioning(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
table := dataset.Table(tableIDs.New())
schema := Schema{
{Name: "name", Type: StringFieldType},
{Name: "somevalue", Type: IntegerFieldType},
}
wantedRange := &RangePartitioningRange{
Start: 0,
End: 135,
Interval: 25,
}
wantedPartitioning := &RangePartitioning{
Field: "somevalue",
Range: wantedRange,
}
err := table.Create(context.Background(), &TableMetadata{
Schema: schema,
RangePartitioning: wantedPartitioning,
})
if err != nil {
t.Fatal(err)
}
defer table.Delete(ctx)
md, err := table.Metadata(ctx)
if err != nil {
t.Fatal(err)
}
if md.RangePartitioning == nil {
t.Fatal("expected range partitioning, got nil")
}
got := md.RangePartitioning.Field
if wantedPartitioning.Field != got {
t.Errorf("RangePartitioning Field: got %v, want %v", got, wantedPartitioning.Field)
}
if md.RangePartitioning.Range == nil {
t.Fatal("expected a range definition, got nil")
}
gotInt64 := md.RangePartitioning.Range.Start
if gotInt64 != wantedRange.Start {
t.Errorf("Range.Start: got %v, wanted %v", gotInt64, wantedRange.Start)
}
gotInt64 = md.RangePartitioning.Range.End
if gotInt64 != wantedRange.End {
t.Errorf("Range.End: got %v, wanted %v", gotInt64, wantedRange.End)
}
gotInt64 = md.RangePartitioning.Range.Interval
if gotInt64 != wantedRange.Interval {
t.Errorf("Range.Interval: got %v, wanted %v", gotInt64, wantedRange.Interval)
}
}
func TestIntegration_RemoveTimePartitioning(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
table := dataset.Table(tableIDs.New())
want := 24 * time.Hour
err := table.Create(ctx, &TableMetadata{
ExpirationTime: testTableExpiration,
TimePartitioning: &TimePartitioning{
Expiration: want,
},
})
if err != nil {
t.Fatal(err)
}
defer table.Delete(ctx)
md, err := table.Metadata(ctx)
if err != nil {
t.Fatal(err)
}
if got := md.TimePartitioning.Expiration; got != want {
t.Fatalf("TimePartitioning expiration want = %v, got = %v", want, got)
}
// Remove time partitioning expiration
md, err = table.Update(context.Background(), TableMetadataToUpdate{
TimePartitioning: &TimePartitioning{Expiration: 0},
}, md.ETag)
if err != nil {
t.Fatal(err)
}
want = time.Duration(0)
if got := md.TimePartitioning.Expiration; got != want {
t.Fatalf("TimeParitioning expiration want = %v, got = %v", want, got)
}
}
// setupPolicyTag is a helper for setting up policy tags in the datacatalog service.
//
// It returns a string for a policy tag identifier and a cleanup function, or an error.
func setupPolicyTag(ctx context.Context) (string, func(), error) {
location := "us"
req := &datacatalogpb.CreateTaxonomyRequest{
Parent: fmt.Sprintf("projects/%s/locations/%s", testutil.ProjID(), location),
Taxonomy: &datacatalogpb.Taxonomy{
// DisplayName must be unique across org.
DisplayName: fmt.Sprintf("google-cloud-go bigquery testing taxonomy %d", time.Now().UnixNano()),
Description: "Taxonomy created for google-cloud-go integration tests",
ActivatedPolicyTypes: []datacatalogpb.Taxonomy_PolicyType{
datacatalogpb.Taxonomy_FINE_GRAINED_ACCESS_CONTROL,
},
},
}
resp, err := policyTagManagerClient.CreateTaxonomy(ctx, req)
if err != nil {
return "", nil, fmt.Errorf("datacatalog.CreateTaxonomy: %v", err)
}
taxonomyID := resp.GetName()
cleanupFunc := func() {
policyTagManagerClient.DeleteTaxonomy(ctx, &datacatalogpb.DeleteTaxonomyRequest{
Name: taxonomyID,
})
}
tagReq := &datacatalogpb.CreatePolicyTagRequest{
Parent: resp.GetName(),
PolicyTag: &datacatalogpb.PolicyTag{
DisplayName: "ExamplePolicyTag",
},
}
tagResp, err := policyTagManagerClient.CreatePolicyTag(ctx, tagReq)
if err != nil {
// we're failed to create tags, but we did create taxonomy. clean it up and signal error.
cleanupFunc()
return "", nil, fmt.Errorf("datacatalog.CreatePolicyTag: %v", err)
}
return tagResp.GetName(), cleanupFunc, nil
}
func TestIntegration_ColumnACLs(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
testSchema := Schema{
{Name: "name", Type: StringFieldType},
{Name: "ssn", Type: StringFieldType},
{Name: "acct_balance", Type: NumericFieldType},
}
table := newTable(t, testSchema)
defer table.Delete(ctx)
tagID, cleanupFunc, err := setupPolicyTag(ctx)
if err != nil {
t.Fatalf("failed to setup policy tag resources: %v", err)
}
defer cleanupFunc()
// amend the test schema to add a policy tag
testSchema[1].PolicyTags = &PolicyTagList{
Names: []string{tagID},
}
// Test: Amend an existing schema with a policy tag.
_, err = table.Update(ctx, TableMetadataToUpdate{
Schema: testSchema,
}, "")
if err != nil {
t.Errorf("update with policyTag failed: %v", err)
}
// Test: Create a new table with a policy tag defined.
newTable := dataset.Table(tableIDs.New())
if err = newTable.Create(ctx, &TableMetadata{
Schema: schema,
Description: "foo",
}); err != nil {
t.Errorf("failed to create new table with policy tag: %v", err)
}
}
func TestIntegration_SimpleRowResults(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
testCases := []struct {
description string
query string
want [][]Value
}{
{
description: "literals",
query: "select 17 as foo",
want: [][]Value{{int64(17)}},
},
{
description: "empty results",
query: "SELECT * FROM (select 17 as foo) where false",
want: [][]Value{},
},
{
// Previously this would return rows due to the destination reference being present
// in the job config, but switching to relying on jobs.getQueryResults allows the
// service to decide the behavior.
description: "ctas ddl",
query: fmt.Sprintf("CREATE TABLE %s.%s AS SELECT 17 as foo", dataset.DatasetID, tableIDs.New()),
want: nil,
},
{
// This is a longer running query to ensure probing works as expected.
description: "long running",
query: "select count(*) from unnest(generate_array(1,1000000)), unnest(generate_array(1, 1000)) as foo",
want: [][]Value{{int64(1000000000)}},
},
}
for _, tc := range testCases {
curCase := tc
t.Run(curCase.description, func(t *testing.T) {
t.Parallel()
q := client.Query(curCase.query)
it, err := q.Read(ctx)
if err != nil {
t.Fatalf("%s read error: %v", curCase.description, err)
}
checkReadAndTotalRows(t, curCase.description, it, curCase.want)
})
}
}
func TestIntegration_QueryIterationPager(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
sql := `
SELECT
num,
num * 2 as double
FROM
UNNEST(GENERATE_ARRAY(1,5)) as num`
q := client.Query(sql)
it, err := q.Read(ctx)
if err != nil {
t.Fatalf("Read: %v", err)
}
pager := iterator.NewPager(it, 2, "")
rowsFetched := 0
for {
var rows [][]Value
nextPageToken, err := pager.NextPage(&rows)
if err != nil {
t.Fatalf("NextPage: %v", err)
}
rowsFetched = rowsFetched + len(rows)
if nextPageToken == "" {
break
}
}
wantRows := 5
if rowsFetched != wantRows {
t.Errorf("Expected %d rows, got %d", wantRows, rowsFetched)
}
}
func TestIntegration_RoutineStoredProcedure(t *testing.T) {
// Verifies we're exhibiting documented behavior, where we're expected
// to return the last resultset in a script as the response from a script
// job.
// https://github.com/googleapis/google-cloud-go/issues/1974
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
// Define a simple stored procedure via DDL.
routineID := routineIDs.New()
routine := dataset.Routine(routineID)
routineSQLID, _ := routine.Identifier(StandardSQLID)
sql := fmt.Sprintf(`
CREATE OR REPLACE PROCEDURE %s(val INT64)
BEGIN
SELECT CURRENT_TIMESTAMP() as ts;
SELECT val * 2 as f2;
END`,
routineSQLID)
if _, _, err := runQuerySQL(ctx, sql); err != nil {
t.Fatal(err)
}
defer routine.Delete(ctx)
// Invoke the stored procedure.
sql = fmt.Sprintf(`
CALL %s(5)`,
routineSQLID)
q := client.Query(sql)
it, err := q.Read(ctx)
if err != nil {
t.Fatalf("query.Read: %v", err)
}
checkReadAndTotalRows(t,
"expect result set from procedure",
it, [][]Value{{int64(10)}})
}
func TestIntegration_RoutineUserTVF(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
routineID := routineIDs.New()
routine := dataset.Routine(routineID)
inMeta := &RoutineMetadata{
Type: "TABLE_VALUED_FUNCTION",
Language: "SQL",
Arguments: []*RoutineArgument{
{Name: "filter",
DataType: &StandardSQLDataType{TypeKind: "INT64"},
}},
ReturnTableType: &StandardSQLTableType{
Columns: []*StandardSQLField{
{Name: "x", Type: &StandardSQLDataType{TypeKind: "INT64"}},
},
},
Body: "SELECT x FROM UNNEST([1,2,3]) x WHERE x = filter",
}
if err := routine.Create(ctx, inMeta); err != nil {
t.Fatalf("routine create: %v", err)
}
defer routine.Delete(ctx)
meta, err := routine.Metadata(ctx)
if err != nil {
t.Fatal(err)
}
// Now, compare the input meta to the output meta
if diff := testutil.Diff(inMeta, meta, cmpopts.IgnoreFields(RoutineMetadata{}, "CreationTime", "LastModifiedTime", "ETag")); diff != "" {
t.Errorf("routine metadata differs, got=-, want=+\n%s", diff)
}
}
func TestIntegration_InsertErrors(t *testing.T) {
// This test serves to verify streaming behavior in the face of oversized data.
// BigQuery will reject insertAll payloads that exceed a defined limit (10MB).
// Additionally, if a payload vastly exceeds this limit, the request is rejected
// by the intermediate architecture.
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
table := newTable(t, schema)
defer table.Delete(ctx)
ins := table.Inserter()
var saverRows []*ValuesSaver
// badSaver represents an excessively sized (>10MB) row message for insertion.
badSaver := &ValuesSaver{
Schema: schema,
InsertID: NoDedupeID,
Row: []Value{strings.Repeat("X", 10485760), []Value{int64(1)}, []Value{true}},
}
saverRows = append(saverRows, badSaver)
err := ins.Put(ctx, saverRows)
if err == nil {
t.Errorf("Wanted row size error, got successful insert.")
}
var e1 *googleapi.Error
ok := errors.As(err, &e1)
if !ok {
t.Errorf("Wanted googleapi.Error, got: %v", err)
}
if e1.Code != http.StatusRequestEntityTooLarge {
want := "Request payload size exceeds the limit"
if !strings.Contains(e1.Message, want) {
t.Errorf("Error didn't contain expected message (%s): %#v", want, e1)
}
}
// Case 2: Very Large Request
// Request so large it gets rejected by intermediate infra (3x 10MB rows)
saverRows = append(saverRows, badSaver)
saverRows = append(saverRows, badSaver)
err = ins.Put(ctx, saverRows)
if err == nil {
t.Errorf("Wanted error, got successful insert.")
}
var e2 *googleapi.Error
ok = errors.As(err, &e2)
if !ok {
t.Errorf("wanted googleapi.Error, got: %v", err)
}
if e2.Code != http.StatusBadRequest && e2.Code != http.StatusRequestEntityTooLarge {
t.Errorf("Wanted HTTP 400 or 413, got %d", e2.Code)
}
}
func TestIntegration_InsertAndRead(t *testing.T) {
if client == nil {
t.Skip("Integration tests skipped")
}
ctx := context.Background()
table := newTable(t, schema)
defer table.Delete(ctx)
// Populate the table.
ins := table.Inserter()
var (
wantRows [][]Value
saverRows []*ValuesSaver
)
for i, name := range []string{"a", "b", "c"} {
row := []Value{name, []Value{int64(i)}, []Value{true}}
wantRows = append(wantRows, row)
saverRows = append(saverRows, &ValuesSaver{
Schema: schema,
InsertID: name,
Row: row,
})
}
if err := ins.Put(ctx, saverRows); err != nil {
t.Fatal(putError(err))
}
// Wait until the data has been uploaded. This can take a few seconds, according
// to https://cloud.google.com/bigquery/streaming-data-into-bigquery.
if err := waitForRow(ctx, table); err != nil {
t.Fatal(err)
}
// Read the table.
checkRead(t, "upload", table.Read(ctx), wantRows)
// Query the table.
q := client.Query(fmt.Sprintf("select name, nums, rec from %s", table.TableID))
q.DefaultProjectID = dataset.ProjectID
q.DefaultDatasetID = dataset.DatasetID
rit, err := q.Read(ctx)
if err != nil {
t.Fatal(err)
}
checkRead(t, "query", rit, wantRows)
// Query the long way.
job1, err := q.Run(ctx)
if err != nil {
t.Fatal(err)
}
if job1.LastStatus() == nil {
t.Error("no LastStatus")
}
job2, err := client.JobFromID(ctx, job1.ID())
if err != nil {
t.Fatal(err)
}
if job2.LastStatus() == nil {
t.Error("no LastStatus")
}
rit, err = job2.Read(ctx)
if err != nil {
t.Fatal(err)
}
checkRead(t, "job.Read", rit, wantRows)
// Get statistics.
jobStatus, err := job2.Status(ctx)
if err != nil {
t.Fatal(err)
}
if jobStatus.Statistics == nil {
t.Fatal("jobStatus missing statistics")
}
if _, ok := jobStatus.Statistics.Details.(*QueryStatistics); !ok {
t.Errorf("expected QueryStatistics, got %T", jobStatus.Statistics.Details)
}
// Test reading directly into a []Value.
valueLists, schema, _, err := readAll(table.Read(ctx))
if err != nil {
t.Fatal(err)
}
it := table.Read(ctx)
for i, vl := range valueLists {
var got []Value
if err := it.Next(&got); err != nil {
t.Fatal(err)
}
if !testutil.Equal(it.Schema, schema) {
t.Fatalf("got schema %v, want %v", it.Schema, schema)
}
want := []Value(vl)
if !testutil.Equal(got, want) {
t.Errorf("%d: got %v, want %v", i, got, want)
}
}
// Test reading into a map.
it = table.Read(ctx)
for _, vl := range valueLists {
var vm map[string]Value