-
Notifications
You must be signed in to change notification settings - Fork 226
Expand file tree
/
Copy pathtest_utils.go
More file actions
1646 lines (1463 loc) · 57.3 KB
/
test_utils.go
File metadata and controls
1646 lines (1463 loc) · 57.3 KB
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
package testutils
import (
"context"
"fmt"
"os"
"path/filepath"
"slices"
"strings"
"testing"
"time"
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/spark-connect-go/v35/spark/sql"
"github.com/apache/spark-connect-go/v35/spark/sql/types"
"github.com/datazip-inc/olake/constants"
"github.com/datazip-inc/olake/utils"
"github.com/datazip-inc/olake/utils/logger"
"github.com/datazip-inc/olake/utils/typeutils"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/moby/moby/api/types/container"
// load pq driver for SQL tests
_ "github.com/lib/pq"
"github.com/stretchr/testify/require"
"github.com/testcontainers/testcontainers-go"
)
const (
icebergCatalog = "olake_iceberg"
sparkConnectAddress = "sc://localhost:15002"
installCmd = "apt-get update && apt-get install -y openjdk-17-jre-headless maven default-mysql-client postgresql postgresql-client wget gnupg iproute2 dnsutils iputils-ping netcat-openbsd nodejs npm jq && wget -qO - https://www.mongodb.org/static/pgp/server-8.0.asc | gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg && echo 'deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/debian bookworm/mongodb-org/8.0 main' | tee /etc/apt/sources.list.d/mongodb-org-8.0.list && apt-get update && apt-get install -y mongodb-mongosh && npm install -g chalk-cli"
SyncTimeout = 10 * time.Minute
BenchmarkThreshold = 0.9
maxRPSHistorySize = 5
)
type IntegrationTest struct {
TestConfig *TestConfig
ExpectedData map[string]interface{}
ExpectedUpdatedData map[string]interface{}
DestinationDataTypeSchema map[string]string
UpdatedDestinationDataTypeSchema map[string]string
DefaultCDCColumnsSchema map[string]string
Namespace string
ExecuteQuery func(ctx context.Context, t *testing.T, streams []string, operation string, fileConfig bool)
DestinationDB string
CursorField string
PartitionRegex string
FilterConfig string
ColumnToExclude string
}
type PerformanceTest struct {
TestConfig *TestConfig
Namespace string
BackfillStreams []string
CDCStreams []string
ExecuteQuery func(ctx context.Context, t *testing.T, streams []string, operation string, fileConfig bool)
}
type SyncSpeed struct {
Speed string `json:"Speed"`
}
type TestConfig struct {
Driver string
HostRootPath string
SourcePath string
CatalogPath string
IcebergDestinationPath string
ParquetDestinationPath string
StatePath string
StatsPath string
BenchmarksPath string
HostTestDataPath string
HostCatalogPath string
HostTestCatalogPath string
DataFormat string
}
// history stores the RPS values and the last updated time for a given mode.
type history struct {
RPS []float64 `json:"rps"`
UpdatedAt time.Time `json:"updated_at"`
}
// benchmarkStore stores the benchmark RPS history for backfill and CDC modes.
type benchmarkStore struct {
Backfill history `json:"backfill"`
CDC history `json:"cdc"`
FilePath string `json:"-"`
}
// initializes the benchmark store with the given path and loads the stored benchmarks data from the file.
func loadBenchmarks(path string) (*benchmarkStore, error) {
store := &benchmarkStore{
Backfill: history{
RPS: make([]float64, 0, maxRPSHistorySize),
UpdatedAt: time.Now().UTC(),
},
CDC: history{
RPS: make([]float64, 0, maxRPSHistorySize),
UpdatedAt: time.Now().UTC(),
},
FilePath: path,
}
if err := store.load(); err != nil {
return nil, err
}
return store, nil
}
// load loads the stored benchmarks data from the file.
func (s *benchmarkStore) load() error {
if err := utils.UnmarshalFile(s.FilePath, s, false); err != nil {
if _, statErr := os.Stat(s.FilePath); os.IsNotExist(statErr) {
// Missing file is acceptable, it will be created when the first RPS is recorded.
return nil
}
return fmt.Errorf("failed to load rps benchmarks from file %s: %s", s.FilePath, err)
}
return nil
}
// record records a new benchmark RPS value for the given driver and mode, and persists it to the file.
func (s *benchmarkStore) record(
isBackfill bool,
rps float64,
) error {
rpsValues := utils.Ternary(
isBackfill,
s.Backfill.RPS,
s.CDC.RPS,
).([]float64)
rpsValues = append(rpsValues, rps)
// Truncate history to maintain a rolling window of the last maxRPSHistorySize values.
if len(rpsValues) > maxRPSHistorySize {
rpsValues = rpsValues[1:]
}
if isBackfill {
s.Backfill.RPS = rpsValues
s.Backfill.UpdatedAt = time.Now().UTC()
} else {
s.CDC.RPS = rpsValues
s.CDC.UpdatedAt = time.Now().UTC()
}
return logger.FileLoggerWithPath(s, s.FilePath)
}
// stats returns the average RPS and count of past RPS values for the given driver and mode.
// The count cannot exceed maxRPSHistorySize.
func (s *benchmarkStore) stats(
isBackfill bool,
) (averageRPS float64, observations int) {
rpsValues := utils.Ternary(
isBackfill,
s.Backfill.RPS,
s.CDC.RPS,
).([]float64)
if len(rpsValues) == 0 {
// No benchmarks recorded for this mode yet.
return 0, 0
}
return utils.Average(rpsValues), len(rpsValues)
}
// GetTestConfig returns the test config for the given driver
func GetTestConfig(driver string, extraParams ...string) *TestConfig {
// pwd is olake/drivers/(driver)/internal
pwd, err := os.Getwd()
if err != nil {
panic(err)
}
// root path is olake's root path
rootPath := filepath.Join(pwd, "../../..")
dataFormat := ""
if len(extraParams) > 0 {
dataFormat = extraParams[0]
}
containerTestDataPath := "/test-olake/drivers/%s/internal/testdata/%s"
hostTestDataPath := filepath.Join(rootPath, "drivers", "%s", "internal", "testdata", dataFormat, "%s")
return &TestConfig{
Driver: driver,
HostRootPath: rootPath,
DataFormat: dataFormat,
HostTestDataPath: fmt.Sprintf(hostTestDataPath, driver, ""),
HostTestCatalogPath: fmt.Sprintf(hostTestDataPath, driver, "test_streams.json"),
HostCatalogPath: fmt.Sprintf(hostTestDataPath, driver, "streams.json"),
BenchmarksPath: fmt.Sprintf(hostTestDataPath, driver, "benchmarks.json"),
SourcePath: fmt.Sprintf(containerTestDataPath, driver, "source.json"),
CatalogPath: fmt.Sprintf(containerTestDataPath, driver, "streams.json"),
IcebergDestinationPath: fmt.Sprintf(containerTestDataPath, driver, "iceberg_destination.json"),
ParquetDestinationPath: fmt.Sprintf(containerTestDataPath, driver, "parquet_destination.json"),
StatePath: fmt.Sprintf(containerTestDataPath, driver, "state.json"),
StatsPath: fmt.Sprintf(containerTestDataPath, driver, "stats.json"),
}
}
func syncCommand(config TestConfig, useState bool, destinationType string, flags ...string) string {
baseCmd := fmt.Sprintf("/test-olake/build.sh driver-%s sync --config %s --catalog %s", config.Driver, config.SourcePath, config.CatalogPath)
switch destinationType {
case "iceberg":
baseCmd = fmt.Sprintf("%s --destination %s", baseCmd, config.IcebergDestinationPath)
case "parquet":
baseCmd = fmt.Sprintf("%s --destination %s", baseCmd, config.ParquetDestinationPath)
}
if useState {
baseCmd = fmt.Sprintf("%s --state %s", baseCmd, config.StatePath)
}
if len(flags) > 0 {
baseCmd = fmt.Sprintf("%s %s", baseCmd, strings.Join(flags, " "))
}
return baseCmd
}
// pass flags as `--flag1, flag1 value, --flag2, flag2 value...`
func discoverCommand(config TestConfig, flags ...string) string {
baseCmd := fmt.Sprintf("/test-olake/build.sh driver-%s discover --config %s", config.Driver, config.SourcePath)
if len(flags) > 0 {
baseCmd = fmt.Sprintf("%s %s", baseCmd, strings.Join(flags, " "))
}
return baseCmd
}
// update normalization=true, partition_regex, and filter_input for selected streams under selected_streams.<namespace> by name
func updateSelectedStreamsCommand(config TestConfig, namespace, partitionRegex, filterConfig string, stream []string, isBackfill bool, columnToExclude string) string {
if len(stream) == 0 {
return ""
}
streamConditions := make([]string, len(stream))
for i, s := range stream {
s = utils.Ternary(slices.Contains(constants.SkipCDCDrivers, constants.DriverType(config.Driver)), strings.ToUpper(s), s).(string)
streamConditions[i] = fmt.Sprintf(`.stream_name == "%s"`, s)
}
condition := strings.Join(streamConditions, " or ")
tmpCatalog := fmt.Sprintf("/tmp/%s_%s_streams.json", config.Driver, utils.Ternary(isBackfill, "backfill", "cdc").(string))
if filterConfig == "" {
filterConfig = "{}"
}
jqExpr := fmt.Sprintf(
`jq --argjson filter '%s' --arg col '%s' '.selected_streams = { "%s": (.selected_streams["%s"] | map(select(%s) | .normalization = true | .partition_regex = "%s" | .filter_config = $filter | .selected_columns.columns -= [$col])) }' %s > %s && mv %s %s`,
filterConfig,
columnToExclude,
namespace,
namespace,
condition,
partitionRegex,
config.CatalogPath,
tmpCatalog,
tmpCatalog,
config.CatalogPath,
)
return jqExpr
}
// set sync_mode and cursor_field for a specific stream object in streams[] by namespace+name
func updateStreamConfigCommand(config TestConfig, namespace, streamName, syncMode, cursorField string) string {
// in case of Oracle, the stream names are in uppercase in stream.json
streamName = utils.Ternary(slices.Contains(constants.SkipCDCDrivers, constants.DriverType(config.Driver)), strings.ToUpper(streamName), streamName).(string)
tmpCatalog := fmt.Sprintf("/tmp/%s_set_mode_streams.json", config.Driver)
// map/select pattern updates nested array members
return fmt.Sprintf(
`jq --arg ns "%s" --arg name "%s" --arg mode "%s" --arg cursor "%s" '.streams = (.streams | map(if .stream.namespace == $ns and .stream.name == $name then (.stream.sync_mode = $mode | .stream.cursor_field = $cursor) else . end))' %s > %s && mv %s %s`,
namespace, streamName, syncMode, cursorField,
config.CatalogPath, tmpCatalog, tmpCatalog, config.CatalogPath,
)
}
// reset state file so incremental can perform initial load (equivalent to full load on first run)
func resetStateFileCommand(config TestConfig) string {
// Ensure the state is clean irrespective of previous CDC run
return fmt.Sprintf(`rm -f %s; echo '{}' > %s`, config.StatePath, config.StatePath)
}
func toggleArrowIcebergWrites(config TestConfig, enabled bool) string {
tmpDest := "/tmp/iceberg_destination.json"
return fmt.Sprintf(
`jq '.writer.arrow_writes = %t' %s > %s && mv %s %s`,
enabled, config.IcebergDestinationPath, tmpDest, tmpDest, config.IcebergDestinationPath,
)
}
// to get backfill streams from cdc streams e.g. "demo_cdc" -> "demo"
func GetBackfillStreamsFromCDC(cdcStreams []string) []string {
backfillStreams := []string{}
for _, stream := range cdcStreams {
backfillStreams = append(backfillStreams, strings.TrimSuffix(stream, "_cdc"))
}
return backfillStreams
}
// reset table and add back data to the table
func (cfg *IntegrationTest) resetTable(ctx context.Context, t *testing.T, testTable string) error {
cfg.ExecuteQuery(ctx, t, []string{testTable}, "drop", false)
cfg.ExecuteQuery(ctx, t, []string{testTable}, "create", false)
cfg.ExecuteQuery(ctx, t, []string{testTable}, "add", false)
if cfg.TestConfig.Driver == string(constants.DB2) {
// to populate stats for DB2
cfg.ExecuteQuery(ctx, t, []string{testTable}, "populate-stats", false)
}
return nil
}
// DeleteParquetFiles deletes only .parquet files directly in the table folder in MinIO
func DeleteParquetFiles(t *testing.T, parquetDB, tableName string) error {
t.Helper()
bucketName := "warehouse"
parquetPath := fmt.Sprintf("%s/%s/", parquetDB, tableName)
t.Logf("Cleaning up .parquet files in: s3a://%s/%s", bucketName, parquetPath)
minioClient, err := minio.New("localhost:9000", &minio.Options{
Creds: credentials.NewStaticV4("admin", "password", ""),
Secure: false,
})
if err != nil {
return fmt.Errorf("failed to create MinIO client: %s", err)
}
ctx := context.Background()
objectsCh := minioClient.ListObjects(ctx, bucketName, minio.ListObjectsOptions{
Prefix: parquetPath,
Recursive: false,
})
deletedCount := 0
for object := range objectsCh {
if object.Err != nil {
return fmt.Errorf("error listing objects: %s", object.Err)
}
if strings.HasSuffix(object.Key, ".parquet") {
fileName := strings.TrimPrefix(object.Key, parquetPath)
t.Logf("Deleting: %s", fileName)
err := minioClient.RemoveObject(ctx, bucketName, object.Key, minio.RemoveObjectOptions{})
if err != nil {
return fmt.Errorf("failed to delete %s: %s", object.Key, err)
}
deletedCount++
}
}
t.Logf("--- Cleanup Complete: Deleted %d files ---", deletedCount)
return nil
}
// syncTestCase represents a test case for sync operations
type syncTestCase struct {
name string
operation string
useState bool
opSymbol string
expected map[string]interface{}
}
// runSyncAndVerify executes a sync command and verifies the results in Iceberg
func (cfg *IntegrationTest) runSyncAndVerify(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
useState bool,
destinationType string,
operation string,
opSymbol string,
schema map[string]interface{},
isCDC bool,
) error {
destDBPrefix := utils.Ternary(cfg.TestConfig.DataFormat != "", fmt.Sprintf("integration_%s_%s", cfg.TestConfig.Driver, cfg.TestConfig.DataFormat), fmt.Sprintf("integration_%s", cfg.TestConfig.Driver)).(string)
cmd := syncCommand(*cfg.TestConfig, useState, destinationType, "--destination-database-prefix", destDBPrefix)
// Execute operation before sync if needed
if useState && operation != "" {
cfg.ExecuteQuery(ctx, t, []string{testTable}, operation, false)
if cfg.TestConfig.Driver == "mssql" {
t.Log("Waiting 20 seconds for MSSQL CDC to process transactions...")
time.Sleep(20 * time.Second)
}
}
// Run sync command
code, out, err := utils.ExecCommand(ctx, c, cmd)
if err != nil || code != 0 {
return fmt.Errorf("sync failed (%d): %s\n%s", code, err, out)
}
t.Logf("Sync successful for %s driver", cfg.TestConfig.Driver)
// Use evolved schema only for CDC "update" operation (where schema evolution is expected)
// Incremental "insert" uses opSymbol "u" but doesn't have schema evolution
evolvedSchema := operation == "update"
switch destinationType {
case "iceberg":
{
if evolvedSchema {
VerifyIcebergSync(t, testTable, cfg.DestinationDB, cfg.UpdatedDestinationDataTypeSchema, cfg.DefaultCDCColumnsSchema, schema, opSymbol, cfg.PartitionRegex, cfg.TestConfig.Driver, isCDC, cfg.ColumnToExclude)
} else {
VerifyIcebergSync(t, testTable, cfg.DestinationDB, cfg.DestinationDataTypeSchema, cfg.DefaultCDCColumnsSchema, schema, opSymbol, cfg.PartitionRegex, cfg.TestConfig.Driver, isCDC, cfg.ColumnToExclude)
}
}
case "parquet":
{
if evolvedSchema {
VerifyParquetSync(t, testTable, cfg.DestinationDB, cfg.UpdatedDestinationDataTypeSchema, cfg.DefaultCDCColumnsSchema, schema, opSymbol, cfg.TestConfig.Driver, isCDC, cfg.ColumnToExclude)
} else {
VerifyParquetSync(t, testTable, cfg.DestinationDB, cfg.DestinationDataTypeSchema, cfg.DefaultCDCColumnsSchema, schema, opSymbol, cfg.TestConfig.Driver, isCDC, cfg.ColumnToExclude)
}
}
}
return nil
}
func (cfg *IntegrationTest) testIcebergWriter(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
useArrowWriter bool,
testFunc func(context.Context, *testing.T, testcontainers.Container, string) error,
) error {
cmd := toggleArrowIcebergWrites(*cfg.TestConfig, useArrowWriter)
code, out, err := utils.ExecCommand(ctx, c, cmd)
if err != nil || code != 0 {
return fmt.Errorf("failed to toggle arrow_writes (%d): %s\n%s", code, err, out)
}
return testFunc(ctx, t, c, testTable)
}
// testIcebergFullLoadAndCDC tests Full load and CDC operations
func (cfg *IntegrationTest) testIcebergFullLoadAndCDC(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
) error {
t.Log("Starting Iceberg Full load + CDC tests")
if err := cfg.resetTable(ctx, t, testTable); err != nil {
return fmt.Errorf("failed to reset table: %w", err)
}
dbTestCases := []syncTestCase{
{
name: "Full-Refresh",
operation: "",
useState: false,
opSymbol: "r",
expected: cfg.ExpectedData,
},
{
name: "CDC - insert",
operation: "insert",
useState: true,
opSymbol: "c",
expected: cfg.ExpectedData,
},
{
name: "CDC - update",
operation: "update",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedUpdatedData,
},
{
name: "CDC - delete",
operation: "delete",
useState: true,
opSymbol: "d",
expected: nil,
},
}
kafkaTestCases := []syncTestCase{
{
name: "CDC - strict - insert",
operation: "",
useState: false,
opSymbol: "c",
expected: cfg.ExpectedData,
},
{
name: "CDC - strict - update",
operation: "update",
useState: true,
opSymbol: "c",
expected: cfg.ExpectedUpdatedData,
},
}
testCases := utils.Ternary(cfg.TestConfig.Driver == string(constants.Kafka), kafkaTestCases, dbTestCases).([]syncTestCase)
// Run each test case
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// schema evolution
if tc.operation == "update" {
if cfg.TestConfig.Driver != "mongodb" && cfg.TestConfig.Driver != "mssql" && cfg.TestConfig.Driver != "kafka" {
cfg.ExecuteQuery(ctx, t, []string{testTable}, "evolve-schema", false)
}
}
if err := cfg.runSyncAndVerify(
ctx,
t,
c,
testTable,
tc.useState,
"iceberg",
tc.operation,
tc.opSymbol,
tc.expected,
tc.name != "Full-Refresh",
); err != nil {
t.Fatalf("%s test failed: %v", tc.name, err)
}
})
}
t.Log("Iceberg Full load + CDC tests completed successfully")
// Drop the Iceberg table after all tests are finished
dropIcebergTable(t, testTable, cfg.DestinationDB)
t.Logf("Dropped Iceberg table: %s", testTable)
return nil
}
// testIcebergFullLoadAndCDC tests Full load and CDC operations
func (cfg *IntegrationTest) testParquetFullLoadAndCDC(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
) error {
t.Log("Starting Parquet Full load + CDC tests")
if err := cfg.resetTable(ctx, t, testTable); err != nil {
return fmt.Errorf("failed to reset table: %s", err)
}
dbTestCases := []syncTestCase{
{
name: "Full-Refresh",
operation: "",
useState: false,
opSymbol: "r",
expected: cfg.ExpectedData,
},
{
name: "CDC - insert",
operation: "insert",
useState: true,
opSymbol: "c",
expected: cfg.ExpectedData,
},
{
name: "CDC - update",
operation: "update",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedUpdatedData,
},
{
name: "CDC - delete",
operation: "delete",
useState: true,
opSymbol: "d",
expected: nil,
},
}
kafkaTestCases := []syncTestCase{
{
name: "CDC - strict - insert",
operation: "",
useState: false,
opSymbol: "c",
expected: cfg.ExpectedData,
},
{
name: "CDC - strict - update",
operation: "update",
useState: true,
opSymbol: "c",
expected: cfg.ExpectedUpdatedData,
},
}
testCases := utils.Ternary(cfg.TestConfig.Driver == string(constants.Kafka), kafkaTestCases, dbTestCases).([]syncTestCase)
// Run each test case
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
// schema evolution
if tc.operation == "update" {
if cfg.TestConfig.Driver != "mongodb" && cfg.TestConfig.Driver != "mssql" && cfg.TestConfig.Driver != "kafka" {
cfg.ExecuteQuery(ctx, t, []string{testTable}, "evolve-schema", false)
}
}
// Delete parquet files before next operation to avoid error due to schema changes
if err := DeleteParquetFiles(t, cfg.DestinationDB, testTable); err != nil {
t.Fatalf("Failed to delete parquet files before %s: %v", tc.name, err)
}
if err := cfg.runSyncAndVerify(
ctx,
t,
c,
testTable,
tc.useState,
"parquet",
tc.operation,
tc.opSymbol,
tc.expected,
tc.name != "Full-Refresh",
); err != nil {
t.Fatalf("%s test failed: %v", tc.name, err)
}
})
}
t.Log("Parquet Full load + CDC tests completed successfully")
return nil
}
// TODO: add incremntal test for string time, timestamp with timezone, datetime, float, int as cursor field
// testIcebergFullLoadAndIncremental tests Full load and Incremental operations
func (cfg *IntegrationTest) testIcebergFullLoadAndIncremental(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
) error {
t.Log("Starting Iceberg Full load + Incremental tests")
if err := cfg.resetTable(ctx, t, testTable); err != nil {
return fmt.Errorf("failed to reset table: %s", err)
}
// Patch streams.json: set sync_mode = incremental, cursor_field = "id"
incPatch := updateStreamConfigCommand(*cfg.TestConfig, cfg.Namespace, testTable, "incremental", cfg.CursorField)
code, out, err := utils.ExecCommand(ctx, c, incPatch)
if err != nil || code != 0 {
return fmt.Errorf("failed to patch streams.json for incremental (%d): %s\n%s", code, err, out)
}
// Reset state so initial incremental behaves like a first full incremental load
resetState := resetStateFileCommand(*cfg.TestConfig)
code, out, err = utils.ExecCommand(ctx, c, resetState)
if err != nil || code != 0 {
return fmt.Errorf("failed to reset state for incremental (%d): %s\n%s", code, err, out)
}
// Test cases for incremental sync
incrementalTestCases := []syncTestCase{
{
name: "Full-Refresh",
operation: "",
useState: false,
opSymbol: "r",
expected: cfg.ExpectedData,
},
{
name: "Incremental - insert",
operation: "insert",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedData,
},
{
name: "Incremental - update",
operation: "update",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedUpdatedData,
},
}
// Run each incremental test case
for _, tc := range incrementalTestCases {
t.Run(tc.name, func(t *testing.T) {
// schema evolution
if tc.operation == "update" {
if cfg.TestConfig.Driver != string(constants.MongoDB) && cfg.TestConfig.Driver != "mssql" {
cfg.ExecuteQuery(ctx, t, []string{testTable}, "evolve-schema", false)
}
}
// drop iceberg table before sync
dropIcebergTable(t, testTable, cfg.DestinationDB)
t.Logf("Dropped Iceberg table: %s", testTable)
if err := cfg.runSyncAndVerify(
ctx,
t,
c,
testTable,
tc.useState,
"iceberg",
tc.operation,
tc.opSymbol,
tc.expected,
false,
); err != nil {
t.Fatalf("Incremental test %s failed: %v", tc.name, err)
}
})
}
t.Log("Iceberg Full load + Incremental tests completed successfully")
return nil
}
// testParquetFullLoadAndIncremental tests Full load and Incremental operations for Parquet
func (cfg *IntegrationTest) testParquetFullLoadAndIncremental(
ctx context.Context,
t *testing.T,
c testcontainers.Container,
testTable string,
) error {
t.Log("Starting Parquet Full load + Incremental tests")
if err := cfg.resetTable(ctx, t, testTable); err != nil {
return fmt.Errorf("failed to reset table: %s", err)
}
// Patch streams.json: set sync_mode = incremental, cursor_field = "id"
incPatch := updateStreamConfigCommand(*cfg.TestConfig, cfg.Namespace, testTable, "incremental", cfg.CursorField)
code, out, err := utils.ExecCommand(ctx, c, incPatch)
if err != nil || code != 0 {
return fmt.Errorf("failed to patch streams.json for incremental (%d): %s\n%s", code, err, out)
}
// Reset state so initial incremental behaves like a first full incremental load
resetState := resetStateFileCommand(*cfg.TestConfig)
code, out, err = utils.ExecCommand(ctx, c, resetState)
if err != nil || code != 0 {
return fmt.Errorf("failed to reset state for incremental (%d): %s\n%s", code, err, out)
}
// Test cases for incremental sync
incrementalTestCases := []syncTestCase{
{
name: "Full-Refresh",
operation: "",
useState: false,
opSymbol: "r",
expected: cfg.ExpectedData,
},
{
name: "Incremental - insert",
operation: "insert",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedData,
},
{
name: "Incremental - update",
operation: "update",
useState: true,
opSymbol: "u",
expected: cfg.ExpectedUpdatedData,
},
}
// Run each incremental test case
for _, tc := range incrementalTestCases {
t.Run(tc.name, func(t *testing.T) {
// schema evolution
if tc.operation == "update" {
if cfg.TestConfig.Driver != string(constants.MongoDB) && cfg.TestConfig.Driver != "mssql" {
cfg.ExecuteQuery(ctx, t, []string{testTable}, "evolve-schema", false)
}
}
// Delete parquet files before next operation to avoid error due to schema changes
if err := DeleteParquetFiles(t, cfg.DestinationDB, testTable); err != nil {
t.Fatalf("Failed to delete parquet files before %s: %v", tc.name, err)
}
if err := cfg.runSyncAndVerify(
ctx,
t,
c,
testTable,
tc.useState,
"parquet",
tc.operation,
tc.opSymbol,
tc.expected,
false,
); err != nil {
t.Fatalf("Incremental test %s failed: %v", tc.name, err)
}
})
}
t.Log("Parquet Full load + Incremental tests completed successfully")
return nil
}
func (cfg *IntegrationTest) TestIntegration(t *testing.T) {
ctx := context.Background()
t.Logf("Root Project directory: %s", cfg.TestConfig.HostRootPath)
t.Logf("Test data directory: %s", cfg.TestConfig.HostTestDataPath)
currentTestTable := utils.Ternary(cfg.TestConfig.DataFormat == "", fmt.Sprintf("%s_test_table_olake", cfg.TestConfig.Driver), fmt.Sprintf("%s_%s_test_table_olake", cfg.TestConfig.Driver, cfg.TestConfig.DataFormat)).(string)
t.Run("Discover", func(t *testing.T) {
req := testcontainers.ContainerRequest{
Image: "golang:1.25.9-bookworm",
ImagePlatform: "linux/amd64",
HostConfigModifier: func(hc *container.HostConfig) {
hc.Binds = []string{
fmt.Sprintf("%s:/test-olake:rw", cfg.TestConfig.HostRootPath),
fmt.Sprintf("%s:/test-olake/drivers/%s/internal/testdata:rw", cfg.TestConfig.HostTestDataPath, cfg.TestConfig.Driver),
}
hc.ExtraHosts = append(hc.ExtraHosts, "host.docker.internal:host-gateway")
},
ConfigModifier: func(config *container.Config) {
config.WorkingDir = "/test-olake"
},
Env: map[string]string{
"TELEMETRY_DISABLED": "true",
},
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{
{
PostReadies: []testcontainers.ContainerHook{
func(ctx context.Context, c testcontainers.Container) error {
// 1. Install required tools
if code, out, err := utils.ExecCommand(ctx, c, installCmd); err != nil || code != 0 {
return fmt.Errorf("install failed (%d): %s\n%s", code, err, out)
}
// 2. Query on test table
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "create", false)
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "clean", false)
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "add", false)
// 3. Run discover command
discoverCmd := discoverCommand(*cfg.TestConfig)
if code, out, err := utils.ExecCommand(ctx, c, discoverCmd); err != nil || code != 0 {
return fmt.Errorf("discover failed (%d): %s\n%s", code, err, string(out))
}
// 4. Verify streams.json file
streamsJSON, err := os.ReadFile(cfg.TestConfig.HostTestCatalogPath)
if err != nil {
return fmt.Errorf("failed to read expected streams JSON: %s", err)
}
testStreamsJSON, err := os.ReadFile(cfg.TestConfig.HostCatalogPath)
if err != nil {
return fmt.Errorf("failed to read actual streams JSON: %s", err)
}
if !utils.NormalizedEqual(string(streamsJSON), string(testStreamsJSON)) {
return fmt.Errorf("streams.json does not match expected test_streams.json\nExpected:\n%s\nGot:\n%s", string(streamsJSON), string(testStreamsJSON))
}
t.Logf("Generated streams validated with test streams")
// 5. Clean up
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "drop", false)
t.Logf("%s discover test-container clean up", cfg.TestConfig.Driver)
return nil
},
},
},
},
Cmd: []string{"tail", "-f", "/dev/null"},
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,
Started: true,
})
require.NoError(t, err, "Container startup failed")
defer func() {
if err := container.Terminate(ctx); err != nil {
t.Logf("warning: failed to terminate container: %v", err)
}
}()
})
t.Run("Sync", func(t *testing.T) {
req := testcontainers.ContainerRequest{
Image: "golang:1.25.9-bookworm",
ImagePlatform: "linux/amd64",
HostConfigModifier: func(hc *container.HostConfig) {
hc.Binds = []string{
fmt.Sprintf("%s:/test-olake:rw", cfg.TestConfig.HostRootPath),
fmt.Sprintf("%s:/test-olake/drivers/%s/internal/testdata:rw", cfg.TestConfig.HostTestDataPath, cfg.TestConfig.Driver),
}
hc.ExtraHosts = append(hc.ExtraHosts, "host.docker.internal:host-gateway")
},
ConfigModifier: func(config *container.Config) {
config.WorkingDir = "/test-olake"
},
Env: map[string]string{
"TELEMETRY_DISABLED": "true",
},
LifecycleHooks: []testcontainers.ContainerLifecycleHooks{
{
PostReadies: []testcontainers.ContainerHook{
func(ctx context.Context, c testcontainers.Container) error {
// 1. Install required tools
if code, out, err := utils.ExecCommand(ctx, c, installCmd); err != nil || code != 0 {
return fmt.Errorf("install failed (%d): %s\n%s", code, err, out)
}
// 2. Query on test table
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "create", false)
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "clean", false)
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "add", false)
// streamUpdateCmd := fmt.Sprintf(
// `jq '(.selected_streams[][] | .normalization) = true' %s > /tmp/streams.json && mv /tmp/streams.json %s`,
// cfg.TestConfig.CatalogPath, cfg.TestConfig.CatalogPath,
// )
streamUpdateCmd := updateSelectedStreamsCommand(*cfg.TestConfig, cfg.Namespace, cfg.PartitionRegex, cfg.FilterConfig, []string{currentTestTable}, true, cfg.ColumnToExclude)
if code, out, err := utils.ExecCommand(ctx, c, streamUpdateCmd); err != nil || code != 0 {
return fmt.Errorf("failed to enable normalization and partition regex in streams.json (%d): %s\n%s",
code, err, out,
)
}
t.Logf("Enabled normalization and added partition regex in %s", cfg.TestConfig.CatalogPath)
writerTypes := []struct {
name string
useArrow bool
}{
{"Legacy", false},
{"Arrow", true},
}
// Skip cdc tests for drivers not supporting cdc mode
if !slices.Contains(constants.SkipCDCDrivers, constants.DriverType(cfg.TestConfig.Driver)) {
for _, wt := range writerTypes {
t.Run(fmt.Sprintf("Iceberg (%s) Full load + CDC tests", wt.name), func(t *testing.T) {
if err := cfg.testIcebergWriter(ctx, t, c, currentTestTable, wt.useArrow, cfg.testIcebergFullLoadAndCDC); err != nil {
t.Fatalf("Iceberg (%s) Full load + CDC tests failed: %v", wt.name, err)
}
})
}
t.Run("Parquet Full load + CDC tests", func(t *testing.T) {
if err := cfg.testParquetFullLoadAndCDC(ctx, t, c, currentTestTable); err != nil {
t.Fatalf("Parquet Full load + CDC tests failed: %v", err)
}
})
}
// Skip incremental tests for drivers not supporting incremental mode
if cfg.TestConfig.Driver != string(constants.Kafka) {
for _, wt := range writerTypes {
t.Run(fmt.Sprintf("Iceberg (%s) Full load + Incremental tests", wt.name), func(t *testing.T) {
if err := cfg.testIcebergWriter(ctx, t, c, currentTestTable, wt.useArrow, cfg.testIcebergFullLoadAndIncremental); err != nil {
t.Fatalf("Iceberg (%s) Full load + Incremental tests failed: %v", wt.name, err)
}
})
}
t.Run("Parquet Full load + Incremental tests", func(t *testing.T) {
if err := cfg.testParquetFullLoadAndIncremental(ctx, t, c, currentTestTable); err != nil {
t.Fatalf("Parquet Full load + Incremental tests failed: %v", err)
}
})
}
// 5. Clean up
cfg.ExecuteQuery(ctx, t, []string{currentTestTable}, "drop", false)
t.Logf("%s sync test-container clean up", cfg.TestConfig.Driver)
return nil
},
},
},
},
Cmd: []string{"tail", "-f", "/dev/null"},
}
container, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{
ContainerRequest: req,