-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathintegration_test.go
2117 lines (1855 loc) · 71.6 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 (C) 2024 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 main
import (
"context"
"flag"
"fmt"
"log"
"os"
"reflect"
"strings"
"testing"
"time"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"github.com/docker/docker/api/types/container"
"github.com/gocql/gocql"
"github.com/google/go-cmp/cmp"
"github.com/google/uuid"
"github.com/testcontainers/testcontainers-go"
"github.com/testcontainers/testcontainers-go/wait"
)
var (
secretPath = os.Getenv("INTEGRATION_TEST_CRED_PATH")
credentialsFilePath = "/tmp/keys/service-account.json"
credentialsPath = "/tmp/keys/"
containerImage = "asia-south1-docker.pkg.dev/cassandra-to-spanner/spanner-adaptor-docker/spanner-adaptor:unit-test"
)
var (
isProxy = false
)
const (
keyspace = "keyspace1"
table = "event"
selectQuery = `SELECT event_data, upload_time, user_id FROM keyspace1.event WHERE upload_time = ? AND user_id = ?`
rangeSelect = `SELECT event_data, upload_time, user_id FROM keyspace1.event WHERE user_id = ?;`
insertQuery = `INSERT INTO keyspace1.event (event_data, upload_time, user_id) VALUES (?, ?, ?)`
updateQuery = `update keyspace1.event set event_data = ? where upload_time = ? and user_id = ? ;`
updateQueryWithTTL = `update keyspace1.event using TTL ? set event_data = ? where upload_time = ? and user_id = ? ;`
updateQueryWithTTLAndTS = `update keyspace1.event using TTL ? and timestamp ? set event_data = ? where upload_time = ? and user_id = ? ;`
partialInsertQuery = `INSERT INTO keyspace1.event ( upload_time, user_id) VALUES ( ?, ?)`
insertQueryWithTimestamp = `INSERT INTO keyspace1.event (event_data, upload_time, user_id) VALUES (?, ?, ?) USING TIMESTAMP ?`
insertQueryWithTTL = `INSERT INTO keyspace1.event (event_data, upload_time, user_id) VALUES (?, ?, ?) USING TTL ?`
insertQueryWithTTLAndTS = `INSERT INTO keyspace1.event (event_data, upload_time, user_id) VALUES (?, ?, ?) USING TIMESTAMP ? and TTL ?`
rangeDeleteWithTS = "DELETE FROM keyspace1.event USING TIMESTAMP ? WHERE user_id = ?"
deleteWithTS = "DELETE FROM keyspace1.event USING TIMESTAMP ? WHERE upload_time = ? AND user_id = ?"
basicSelectWithLimit = "SELECT * FROM keyspace1.event limit ?"
selectColWithOrderBy = "SELECT upload_time, event_data FROM keyspace1.event WHERE user_id = ? ORDER BY upload_time ASC;"
)
const (
setupFailedError = "setup failed: %v"
errorWhileDelete = "Error while deleting - %s"
expectedZeroRows = "expected 0 rows post delete operation"
failedToUpdateRow = "failed to update row: %v"
errorWhileInsert = "error occurred while insert"
errorWhileInsertTS = "%s with timestamp & ttl - %s"
errorInSelect = "error in selecting: %v"
errorMoreRowsThanExpected = "Received more rows than expected"
unexpectedRow = "Unexpected row %d: got (%d, %s), expected (%d, %s)"
errorInClosingIter = "error closing iterator: %v"
errorExpectedRows = "Expected %d rows, but got %d"
errorValidationFailed = "Validation failed for %s: expected %v, got %v"
errorValidationType = "Validation failed for %s: expected %s, got %T"
errorQueryFailed = "Query failed: %v"
errorInsertFailed = "Insert failed: %v"
errorWhileExecutingBatch = "Error while executing Batch - %s"
)
const (
typeTime = "time.Time"
typeListOfByte = "[]byte"
typeMapStringBool = "map[string]bool"
typeMapStringString = "map[string]string"
typeMapStringTime = "map[string]time.Time"
typeListOfString = "[]string"
)
const (
insertRow = "insert Row"
updateRow = "Updated Row"
updateInFutureError = "Expected failure as updating in future"
)
var (
session *gocql.Session
)
func fetchAndStoreCredentials(ctx context.Context) error {
if secretPath == "" {
return fmt.Errorf("ENV INTEGRATION_TEST_CRED_PATH IS NOT SET")
}
client, err := secretmanager.NewClient(ctx)
if err != nil {
return fmt.Errorf("failed to create secret manager client: %v", err)
}
defer client.Close()
accessRequest := &secretmanagerpb.AccessSecretVersionRequest{
Name: secretPath,
}
result, err := client.AccessSecretVersion(ctx, accessRequest)
if err != nil {
return fmt.Errorf("failed to access secret version: %v", err)
}
if err := os.MkdirAll(credentialsPath, os.ModePerm); err != nil {
return fmt.Errorf("failed to create directory: %v", err)
}
credentials := string(result.Payload.Data)
err = os.WriteFile(credentialsFilePath, []byte(credentials), 0644)
if err != nil {
return fmt.Errorf("failed to write credentials to file: %v", err)
}
return nil
}
func TestMain(m *testing.M) {
var target string
flag.StringVar(&target, "target", "proxy", "Specify the test target: 'proxy' or 'cassandra'")
flag.Parse()
if target == "" {
target = "proxy"
}
switch target {
case "proxy":
isProxy = true
setupAndRunSpannerProxy(m)
case "cassandra":
isProxy = false
setupAndRunCassandra(m)
default:
log.Fatalf("Invalid target - %s", target)
}
}
func setupAndRunSpannerProxy(m *testing.M) {
ctx := context.Background()
if err := fetchAndStoreCredentials(ctx); err != nil {
log.Fatalf("error while setting up gcp credentials - %v", err)
}
//TODO Get Spanner connection and create/update DDL and tableConfig
// Request a testcontainers.Container object
req := testcontainers.ContainerRequest{
Image: containerImage,
ExposedPorts: []string{"9042/tcp"},
Env: map[string]string{
"GOOGLE_APPLICATION_CREDENTIALS": "/tmp/keys/service-account.json",
},
HostConfigModifier: func(hostConfig *container.HostConfig) {
hostConfig.Binds = []string{
fmt.Sprintf("%s:/tmp/keys/service-account.json", credentialsFilePath),
}
},
WaitingFor: wait.ForLog("proxy is listening").WithStartupTimeout(60 * time.Second),
}
proxyContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
log.Fatalf("Could not start container: %v", err)
}
defer func() {
err := proxyContainer.Terminate(ctx)
log.Fatalf("error while terminating - %v", err.Error())
}()
host, err := proxyContainer.Host(ctx)
if err != nil {
log.Fatalf("Could not get container host: %v", err)
}
mappedPort, err := proxyContainer.MappedPort(ctx, "9042")
if err != nil {
log.Fatalf("Could not get mapped port: %v", err)
}
cluster := gocql.NewCluster(host)
cluster.Port = mappedPort.Int()
cluster.Keyspace = keyspace
cluster.ProtoVersion = 4
session, err = cluster.CreateSession()
if err != nil {
log.Fatalf("Could not connect to Cassandra: %v", err)
}
defer session.Close()
// Run tests
code := m.Run()
// Cleanup
session.Close()
os.Exit(code)
}
func setupAndRunCassandra(m *testing.M) {
// Create a context with a 5-minute timeout
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
defer cancel()
// Fetch and store GCP credentials if needed
if err := fetchAndStoreCredentials(ctx); err != nil {
log.Fatalf("Error while setting up GCP credentials - %v", err)
}
// Define the container request
req := testcontainers.ContainerRequest{
Image: "cassandra:latest",
ExposedPorts: []string{"9042/tcp"}, // Expose the default Cassandra CQL port
Env: map[string]string{
"MAX_HEAP_SIZE": "512M", // Optional tuning for Cassandra
"HEAP_NEWSIZE": "100M",
},
HostConfigModifier: func(hostConfig *container.HostConfig) {
// Optional: Mount GCP credentials if needed
hostConfig.Binds = []string{
fmt.Sprintf("%s:/tmp/keys/service-account.json", credentialsFilePath),
}
},
WaitingFor: wait.ForLog("Starting listening for CQL clients on /0.0.0.0:9042").WithStartupTimeout(120 * time.Second), // Wait until Cassandra is ready
}
// Start the Cassandra container
cassandraContainer, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
if err != nil {
log.Fatalf("Could not start container: %v", err)
}
defer func() {
// Ensure the container is terminated after tests
if err := cassandraContainer.Terminate(ctx); err != nil {
log.Fatalf("Error while terminating container - %v", err)
}
}()
// Get the container host and mapped port for Cassandra
host, err := cassandraContainer.Host(ctx)
if err != nil {
log.Fatalf("Could not get container host: %v", err)
}
mappedPort, err := cassandraContainer.MappedPort(ctx, "9042")
if err != nil {
log.Fatalf("Could not get mapped port: %v", err)
}
// Configure and create a new Cassandra cluster session
cluster := gocql.NewCluster(host)
cluster.Port = mappedPort.Int() // Use the mapped port from the container
cluster.ProtoVersion = 4 // Use protocol version 4
cluster.ConnectTimeout = 30 * time.Second // Set connection timeout
cluster.Keyspace = "system" // Use the default 'system' keyspace initially
// Create a session with Cassandra
session, err = cluster.CreateSession()
if err != nil {
log.Fatalf("Could not connect to Cassandra: %v", err)
}
defer session.Close()
//create Kespace
ddlStatementKeyspace := "CREATE KEYSPACE IF NOT EXISTS keyspace1 WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : '1' };"
if err := session.Query(ddlStatementKeyspace).Exec(); err != nil {
log.Fatalf("Could not create keyspace: %v", err)
}
ddlStatement := "CREATE TABLE IF NOT EXISTS keyspace1.event ( user_id text, upload_time bigint, event_data blob, PRIMARY KEY (user_id, upload_time)) WITH bloom_filter_fp_chance = 0.01;"
if err := session.Query(ddlStatement).Exec(); err != nil {
log.Fatalf("Could not create table: %v", err)
}
ddlStatement = "CREATE TABLE IF NOT EXISTS keyspace1.validate_data_types (text_col text, blob_col blob, timestamp_col TIMESTAMP, int_col int, bigint_col bigint, float_col float, bool_col boolean, uuid_col uuid, map_bool_col map<text, boolean>, map_str_col map<text, text>, map_ts_col map<text, timestamp>, list_str_col list<text>, set_str_col set<text>, PRIMARY KEY (text_col) ) WITH bloom_filter_fp_chance=0.010000;"
if err := session.Query(ddlStatement).Exec(); err != nil {
log.Fatalf("Could not create table: %v", err)
}
// Run the tests
code := m.Run()
// Cleanup and exit
session.Close()
os.Exit(code)
}
func insertData(t *testing.T, session *gocql.Session, commEvent []byte, uploadTime int64, userID string) {
if err := session.Query(insertQuery, commEvent, uploadTime, userID).Exec(); err != nil {
t.Fatalf("failed to insert data: %v, %v , %v, %v", userID, uploadTime, string(commEvent), err)
}
}
func partialInsertData(t *testing.T, session *gocql.Session, uploadTime int64, userID string) {
if err := session.Query(partialInsertQuery, uploadTime, userID).Exec(); err != nil {
t.Fatalf("failed to insert data: %v", err)
}
}
func selectAndValidateData(t *testing.T, session *gocql.Session, expectedCommEvent []byte, expectedUploadTime int64, expectedUserID string) {
var retrievedCommEvent []byte
var retrievedUploadTime int64
var retrievedUserID string
if err := session.Query(selectQuery, expectedUploadTime, expectedUserID).Scan(&retrievedCommEvent, &retrievedUploadTime, &retrievedUserID); err != nil {
t.Fatalf("failed to select data: %v", err)
}
if !cmp.Equal(string(retrievedCommEvent), string(expectedCommEvent)) {
t.Errorf("CommEvent diff: %s", cmp.Diff(string(retrievedCommEvent), string(expectedCommEvent)))
}
if !cmp.Equal(retrievedUploadTime, expectedUploadTime) {
t.Errorf("UploadTime diff: %s", cmp.Diff(retrievedUploadTime, expectedUploadTime))
}
if !cmp.Equal(retrievedUserID, expectedUserID) {
t.Errorf("UserID diff: %s", cmp.Diff(retrievedUserID, expectedUserID))
}
}
func updateData(t *testing.T, session *gocql.Session, commEvent []byte, uploadTime int64, userID string) {
if err := session.Query(updateQuery, commEvent, uploadTime, userID).Exec(); err != nil {
t.Fatalf(failedToUpdateRow, err)
}
}
func TestIntegration_Insert(t *testing.T) {
tests := []struct {
name string
runTest func(t *testing.T)
expectedErr error
}{
{
name: "Basic Insert ",
runTest: func(t *testing.T) {
commEvent := []byte("event data")
uploadTime := int64(1627847284)
userID := uuid.New().String()
insertData(t, session, commEvent, uploadTime, userID)
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Upsert",
runTest: func(t *testing.T) {
commEvent := []byte(updateRow)
uploadTime := int64(1627847284)
userID := uuid.New().String()
insertData(t, session, []byte(insertRow), uploadTime, userID)
insertData(t, session, commEvent, uploadTime, userID) //upsert
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Insert with Future Timestamp",
runTest: func(t *testing.T) {
commEvent := []byte("future event data")
uploadTime := int64(1627847284)
userID := uuid.New().String()
futureTimestamp := time.Now().Add(time.Hour).UnixNano() / int64(time.Microsecond)
err := session.Query(insertQueryWithTimestamp, commEvent, uploadTime, userID, futureTimestamp).Exec()
if isProxy {
if err == nil {
t.Fatalf("expected error on insert with future timestamp, but insert succeeded")
} else {
expectedError := "Cannot write timestamps in the future"
if strings.Contains(err.Error(), expectedError) {
t.Logf("Insert with future timestamp failed as expected: %v", err)
} else {
t.Fatalf("unexpected error message: %v", err)
}
}
} else if err != nil {
t.Errorf("error not expected - %s", err)
}
},
expectedErr: nil,
},
{
name: "Insert with past Timestamp",
runTest: func(t *testing.T) {
commEvent := []byte("past event data")
uploadTime := int64(1627847284)
userID := uuid.New().String()
insertData(t, session, []byte(insertRow), uploadTime, userID)
pastTimestamp := time.Now().Add(-1*time.Hour).UnixNano() / int64(time.Microsecond)
err := session.Query(insertQueryWithTimestamp, commEvent, uploadTime, userID, pastTimestamp).Exec()
if err != nil {
t.Fatalf("Upsert with past timestamp failed")
}
var retrievedCommEvent []byte
var retrievedUploadTime int64
var retrievedUserID string
if err := session.Query(selectQuery, uploadTime, userID).Scan(&retrievedCommEvent, &retrievedUploadTime, &retrievedUserID); err != nil {
t.Fatalf("failed to select data: %v", err)
}
if string(retrievedCommEvent) == string(commEvent) {
t.Error("upsert should be ignored")
}
},
expectedErr: nil,
},
{
name: "Insert with TTL",
runTest: func(t *testing.T) {
commEvent := []byte("event with TTL")
uploadTime := int64(1627847284)
userID := uuid.New().String()
ttl := 10 // 10 seconds
err := session.Query(insertQueryWithTTL, commEvent, uploadTime, userID, ttl).Exec()
if err != nil {
t.Fatalf("%s with ttl - %s", errorWhileInsert, err.Error())
}
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Upsert with TTL",
runTest: func(t *testing.T) {
commEvent := []byte(updateRow)
uploadTime := int64(1627847284)
userID := uuid.New().String()
ttl := 10 // 10 seconds
insertData(t, session, []byte(insertRow), uploadTime, userID)
err := session.Query(insertQueryWithTTL, commEvent, uploadTime, userID, ttl).Exec()
if err != nil {
t.Fatalf("error occurred while Upsert with ttl - %s", err.Error())
}
// Validate data immediately
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Insert with TTL and Timestamp",
runTest: func(t *testing.T) {
commEvent := []byte(insertRow)
uploadTime := int64(1627847284)
userID := uuid.New().String()
timestamp := time.Now().Add(-1*time.Millisecond).UnixNano() / int64(time.Microsecond)
ttl := 10 // 10 seconds
err := session.Query(insertQueryWithTTLAndTS, commEvent, uploadTime, userID, timestamp, ttl).Exec()
if err != nil {
t.Fatalf(errorWhileInsertTS, errorWhileInsert, err.Error())
}
// Validate data immediately
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Upsert with TTL and Timestamp",
runTest: func(t *testing.T) {
commEvent := []byte(updateRow)
uploadTime := int64(16278472894)
userID := uuid.New().String()
timestamp := time.Now().Add(-10*time.Second).UnixNano() / int64(time.Microsecond)
ttl := 10 // 10 seconds
// insert
err := session.Query(insertQueryWithTTLAndTS, commEvent, uploadTime, userID, timestamp, ttl).Exec()
if err != nil {
t.Fatalf(errorWhileInsertTS, errorWhileInsert, err.Error())
}
// update
timestamp += 100
err = session.Query(insertQueryWithTTLAndTS, commEvent, uploadTime, userID, timestamp, ttl).Exec()
if err != nil {
t.Fatalf(errorWhileInsertTS, errorWhileInsert, err.Error())
}
// Validate data immediately
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Partial Insert",
runTest: func(t *testing.T) {
uploadTime := int64(1627847296)
userID := uuid.New().String()
partialInsertData(t, session, uploadTime, userID)
commEvent := []byte("")
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Insert with TTL 0",
runTest: func(t *testing.T) {
commEvent := []byte("event with TTL")
uploadTime := int64(1627847284)
userID := uuid.New().String()
ttl := 0
err := session.Query(insertQueryWithTTL, commEvent, uploadTime, userID, ttl).Exec()
if err != nil {
t.Fatalf("%s with ttl - %s", errorWhileInsert, err.Error())
}
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Upsert with TTL 0 and Timestamp",
runTest: func(t *testing.T) {
commEvent := []byte(updateRow)
uploadTime := int64(16278472894)
userID := uuid.New().String()
timestamp := time.Now().Add(-10*time.Second).UnixNano() / int64(time.Microsecond)
ttl := 0
// insert
err := session.Query(insertQueryWithTTLAndTS, commEvent, uploadTime, userID, timestamp, ttl).Exec()
if err != nil {
t.Fatalf(errorWhileInsertTS, errorWhileInsert, err.Error())
}
// update
timestamp += 100
err = session.Query(insertQueryWithTTLAndTS, commEvent, uploadTime, userID, timestamp, ttl).Exec()
if err != nil {
t.Fatalf(errorWhileInsertTS, errorWhileInsert, err.Error())
}
// Validate data immediately
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.runTest(t)
})
}
}
func TestIntegration_Select(t *testing.T) {
tests := []struct {
name string
runTest func(t *testing.T)
expectedErr error
}{
{
name: "count(*)",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var count int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT count(*) FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if len(columns) == 0 || columns[0].Name != "count" {
t.Errorf("expected column name `count` got `%s` ", columns[0].Name)
}
if iter.Scan(&count) {
if count == 0 {
t.Errorf("expected 1 but got %d", count)
}
} else {
t.Error("error while fetching count value")
}
},
},
{
name: "count(*) as myalias",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var count int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT count(*) as myalias FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if len(columns) == 0 || columns[0].Name != "myalias" {
t.Errorf("expected column name `count` got `%s` ", columns[0].Name)
}
if iter.Scan(&count) {
if count == 0 {
t.Errorf("expected 1 but got %d", count)
}
} else {
t.Error("error while fetching count value")
}
},
},
{
name: "count(column)",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var count int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT count(event_data) FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if isProxy {
if len(columns) == 0 || columns[0].Name != "count_event_data" {
t.Errorf("expected column name `count_event_data` got `%s` ", columns[0].Name)
}
} else {
if len(columns) == 0 || columns[0].Name != "system.count(event_data)" {
t.Errorf("expected column name `system.count(event_data)` got `%s` ", columns[0].Name)
}
}
if iter.Scan(&count) {
if count == 0 {
t.Errorf("expected 1 but got %d", count)
}
} else {
t.Error("error while fetching count value")
}
},
},
{
name: "count(column) as myalias",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var count int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT count(event_data) as myalias FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if len(columns) == 0 || columns[0].Name != "myalias" {
t.Errorf("expected column name `myalias` got `%s` ", columns[0].Name)
}
if iter.Scan(&count) {
if count == 0 {
t.Errorf("expected 1 but got %d", count)
}
} else {
t.Error("error while fetching count value")
}
},
},
{
name: "writetime(column)",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var writetime int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT writetime(event_data) FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if isProxy {
if len(columns) == 0 || columns[0].Name != "writetime_event_data" {
t.Errorf("expected column name `writetime_event_data` got `%s` ", columns[0].Name)
}
} else {
if len(columns) == 0 || columns[0].Name != "writetime(event_data)" {
t.Errorf("expected column name `writetime(event_data)` got `%s` ", columns[0].Name)
}
}
if iter.Scan(&writetime) {
if writetime <= uploadTime {
t.Errorf("expected current_unix_time but got %d", writetime)
}
} else {
t.Error("error while fetching writetime value")
}
},
},
{
name: "writetime(column) as wt",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
var writetime int64
insertData(t, session, []byte(insertRow), uploadTime, userID)
iter := getSelectIter(t, "SELECT writetime(event_data) as wt FROM keyspace1.event WHERE upload_time = ? AND user_id = ?", uploadTime, userID)
defer iter.Close()
columns := iter.Columns()
if len(columns) == 0 || columns[0].Name != "wt" {
t.Errorf("expected column name `wt` got `%s` ", columns[0].Name)
}
if iter.Scan(&writetime) {
if writetime <= uploadTime {
t.Errorf("expected current_unix_time but got %d", writetime)
}
} else {
t.Error("error while fetching writetime value")
}
},
},
{
name: "UnsupportedFunc(column)",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
insertData(t, session, []byte(insertRow), uploadTime, userID)
query := "SELECT xxxx(event_data) FROM keyspace1.event WHERE upload_time = ? AND user_id = ?"
iter := session.Query(query, uploadTime, userID).Iter()
// Check if there is an error in preparing or executing the query
if err := iter.Close(); err == nil {
t.Fatalf("Expected query to fail but it succeeded")
} else {
expectedErrMsg := "Unknown function 'xxxx'"
if err.Error() != expectedErrMsg {
t.Fatalf("Expected error message '%s' but got '%s'", expectedErrMsg, err.Error())
} else {
t.Logf("Query failed as expected with error: %v", err)
}
}
},
},
{
name: "Select col1, col2 from table",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
commEventInsert := []byte(insertRow)
var retrievedUploadTime int64
var commEvent []byte
insertData(t, session, commEventInsert, uploadTime, userID)
query := "SELECT upload_time, event_data FROM keyspace1.event WHERE upload_time = ? AND user_id = ?"
iter := session.Query(query, uploadTime, userID).Iter()
if !iter.Scan(&retrievedUploadTime, &commEvent) {
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
t.Fatalf("No rows returned or error in scanning")
}
if retrievedUploadTime != uploadTime {
t.Errorf("Expected upload_time %d but got %d", uploadTime, retrievedUploadTime)
}
if string(commEvent) != string(commEventInsert) {
t.Errorf("Expected event_data %s but got %s", commEventInsert, commEvent)
}
},
},
{
name: "Limit ",
runTest: func(t *testing.T) {
var limit = 5
iter := session.Query(basicSelectWithLimit, limit).Iter()
if iter.NumRows() < limit || iter.NumRows() == 0 {
t.Fatalf("Expected number of rows >0 and <5 but got %d", iter.NumRows())
}
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
},
},
{
name: "Select with allow filtering",
runTest: func(t *testing.T) {
uploadTime := int64(1627847264)
query := "SELECT * FROM keyspace1.event where upload_time > ? ALLOW FILTERING;"
iter := session.Query(query, uploadTime).Iter()
if iter.NumRows() == 0 {
t.Fatalf("Expected number of rows >0 but got %d", iter.NumRows())
}
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
},
},
{
name: "Order by Desc",
runTest: func(t *testing.T) {
commEvent := []byte(insertRow)
userID := uuid.New().String()
insertData(t, session, commEvent, int64(1627847284), userID)
insertData(t, session, commEvent, int64(1627847286), userID)
insertData(t, session, commEvent, int64(1627847288), userID)
query := "SELECT upload_time FROM keyspace1.event WHERE user_id = ? ORDER BY upload_time DESC;"
iter := session.Query(query, userID).Iter()
var uploadTime int64
var previousUploadTime int64 = int64(1<<63 - 1) // Initialize with the maximum possible int64 value
for iter.Scan(&uploadTime) {
if uploadTime > previousUploadTime {
t.Fatalf("Result is not in descending order: %d came after %d", uploadTime, previousUploadTime)
}
previousUploadTime = uploadTime
}
if iter.NumRows() == 0 {
t.Fatalf("Expected number of rows > 0 but got %d", iter.NumRows())
}
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
},
},
{
name: "Order by ASC",
runTest: func(t *testing.T) {
var uploadTime int64
userID := uuid.New().String()
commEvent := []byte(insertRow)
insertData(t, session, commEvent, int64(1627847284), userID)
insertData(t, session, commEvent, int64(1627847286), userID)
insertData(t, session, commEvent, int64(1627847288), userID)
query := "SELECT upload_time FROM keyspace1.event WHERE user_id = ? ORDER BY upload_time ASC;"
iter := session.Query(query, userID).Iter()
var previousUploadTime int64 = 1
for iter.Scan(&uploadTime) {
if uploadTime < previousUploadTime {
t.Fatalf("Result is not in ascending order: %d came after %d", uploadTime, previousUploadTime)
}
previousUploadTime = uploadTime
}
if iter.NumRows() == 0 {
t.Fatalf("Expected number of rows > 0 but got %d", iter.NumRows())
}
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
},
},
{
name: "Stale Read",
runTest: func(t *testing.T) {
uploadTime := int64(1627847284)
userID := uuid.New().String()
commEventInsert := []byte(insertRow)
var retrievedUploadTime int64
var commEvent []byte
insertData(t, session, commEventInsert, uploadTime, userID)
time.Sleep(time.Second)
customPayload := map[string][]byte{
"spanner_maxstaleness": []byte("1s"),
}
query := "SELECT upload_time, event_data FROM keyspace1.event WHERE upload_time = ? AND user_id = ?"
stmt := session.Query(query, uploadTime, userID)
stmt.CustomPayload(customPayload)
iter := stmt.Iter()
if !iter.Scan(&retrievedUploadTime, &commEvent) {
if err := iter.Close(); err != nil {
t.Fatalf(errorInSelect, err)
}
t.Fatalf("No rows returned or error in scanning")
}
if retrievedUploadTime != uploadTime {
t.Errorf("Expected upload_time %d but got %d", uploadTime, retrievedUploadTime)
}
if string(commEvent) != string(commEventInsert) {
t.Errorf("Expected event_data %s but got %s", commEventInsert, commEvent)
}
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
tt.runTest(t)
})
}
}
func getSelectIter(t *testing.T, query string, args ...interface{}) *gocql.Iter {
iter := session.Query(query, args...).Iter()
if iter.NumRows() == 0 {
t.Fatalf("no rows returned")
}
return iter
}
func TestIntegration_Update(t *testing.T) {
tests := []struct {
name string
runTest func(t *testing.T)
expectedErr error
}{
{
name: "Update",
runTest: func(t *testing.T) {
commEvent := []byte(updateRow)
uploadTime := int64(1627847296)
userID := uuid.New().String()
insertData(t, session, []byte(insertRow), uploadTime, userID)
updateData(t, session, commEvent, uploadTime, userID)
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "TTL",
runTest: func(t *testing.T) {
commEvent := []byte(insertRow)
uploadTime := int64(1627847296)
userID := uuid.New().String()
ttl := 20
insertData(t, session, commEvent, uploadTime, userID)
commEvent = []byte(updateRow)
if err := session.Query(updateQueryWithTTL, ttl, commEvent, uploadTime, userID).Exec(); err != nil {
t.Fatalf(failedToUpdateRow, err)
}
commEvent = []byte(updateRow)
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "TTL with 0",
runTest: func(t *testing.T) {
commEvent := []byte(insertRow)
uploadTime := int64(1627847296)
userID := uuid.New().String()
ttl := 0
insertData(t, session, commEvent, uploadTime, userID)
commEvent = []byte(updateRow)
if err := session.Query(updateQueryWithTTL, ttl, commEvent, uploadTime, userID).Exec(); err != nil {
t.Fatalf(failedToUpdateRow, err)
}
commEvent = []byte(updateRow)
selectAndValidateData(t, session, commEvent, uploadTime, userID)
},
},
{
name: "Update with timestamp val > last update time & ttl ",
runTest: func(t *testing.T) {
commEvent := []byte(insertRow)
uploadTime := int64(1627847296)
userID := uuid.New().String()
ttl := 2000
currentTime := int64(1627847296)
err := session.Query(insertQueryWithTimestamp, commEvent, uploadTime, userID, currentTime).Exec()
if err != nil {
t.Error("insert failed")
}
currentTime = int64(1627947299)
commEvent = []byte(updateRow)
if err := session.Query(updateQueryWithTTLAndTS, ttl, currentTime, commEvent, uploadTime, userID).Exec(); err != nil {
t.Fatalf(failedToUpdateRow, err)