-
Notifications
You must be signed in to change notification settings - Fork 924
/
DataplexFileFormatConversionTest.java
421 lines (367 loc) · 18.5 KB
/
DataplexFileFormatConversionTest.java
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
/*
* Copyright (C) 2021 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 com.google.cloud.teleport.v2.templates;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Asset;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1AssetResourceSpec;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Entity;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Partition;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1Schema;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1SchemaSchemaField;
import com.google.api.services.dataplex.v1.model.GoogleCloudDataplexV1StorageFormat;
import com.google.cloud.teleport.v2.clients.DataplexClient;
import com.google.cloud.teleport.v2.templates.DataplexFileFormatConversion.FileFormatConversionOptions;
import com.google.cloud.teleport.v2.templates.DataplexFileFormatConversion.InputFileFormat;
import com.google.cloud.teleport.v2.transforms.AvroConverters;
import com.google.cloud.teleport.v2.transforms.ParquetConverters;
import com.google.cloud.teleport.v2.utils.FileFormat.FileFormatOptions;
import com.google.cloud.teleport.v2.utils.WriteDisposition.WriteDispositionOptions;
import com.google.cloud.teleport.v2.values.DataplexAssetResourceSpec;
import com.google.cloud.teleport.v2.values.DataplexCompression;
import com.google.cloud.teleport.v2.values.EntityMetadata.StorageSystem;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Resources;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Parser;
import org.apache.avro.generic.GenericData.Record;
import org.apache.avro.generic.GenericRecord;
import org.apache.beam.sdk.options.PipelineOptionsFactory;
import org.apache.beam.sdk.testing.NeedsRunner;
import org.apache.beam.sdk.testing.PAssert;
import org.apache.beam.sdk.testing.TestPipeline;
import org.apache.beam.sdk.values.PCollection;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.rules.TemporaryFolder;
/** Test cases for the {@link DataplexFileFormatConversion} class. */
public class DataplexFileFormatConversionTest {
private static final String RESOURCES_DIR = "DataplexFileFormatConversionTest";
private static final GoogleCloudDataplexV1Schema SCHEMA =
new GoogleCloudDataplexV1Schema()
.setFields(
ImmutableList.of(
new GoogleCloudDataplexV1SchemaSchemaField()
.setName("Word")
.setType("STRING")
.setMode("REQUIRED"),
new GoogleCloudDataplexV1SchemaSchemaField()
.setName("Number")
.setType("INT32")
.setMode("REQUIRED")));
private static final String EXPECT_SERIALIZED_AVRO_SCHEMA =
"{"
+ "\"name\": \"Schema\","
+ "\"type\": \"record\","
+ "\"fields\": ["
+ " {\"name\": \"Word\", \"type\": \"string\"},"
+ " {\"name\": \"Number\", \"type\": \"int\"}"
+ "]"
+ "}";
private static final Schema EXPECTED_AVRO_SCHEMA =
new Parser().parse(EXPECT_SERIALIZED_AVRO_SCHEMA);
private static final ImmutableList<GenericRecord> EXPECTED_GENERIC_RECORDS =
expectedGenericRecords();
private static final GoogleCloudDataplexV1Entity entity1 =
new GoogleCloudDataplexV1Entity()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e1")
.setId("e1")
.setSystem(StorageSystem.CLOUD_STORAGE.name())
.setFormat(new GoogleCloudDataplexV1StorageFormat().setFormat(InputFileFormat.CSV.name()))
.setSchema(SCHEMA);
private static final GoogleCloudDataplexV1Partition partition11 =
new GoogleCloudDataplexV1Partition()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e1/partitions/p11")
.setLocation(Resources.getResource(RESOURCES_DIR + "/entity1/partition11").getPath());
private static final GoogleCloudDataplexV1Partition partition12 =
new GoogleCloudDataplexV1Partition()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e1/partitions/p12")
.setLocation(Resources.getResource(RESOURCES_DIR + "/entity1/partition12").getPath());
private static final GoogleCloudDataplexV1Asset asset2 =
new GoogleCloudDataplexV1Asset()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/assets/a2");
private static final GoogleCloudDataplexV1Entity entity2 =
new GoogleCloudDataplexV1Entity()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e2")
.setId("e2")
.setAsset(asset2.getName())
.setSystem(StorageSystem.CLOUD_STORAGE.name())
.setFormat(
new GoogleCloudDataplexV1StorageFormat().setFormat(InputFileFormat.JSON.name()))
.setDataPath(Resources.getResource(RESOURCES_DIR + "/entity2").getPath())
.setSchema(SCHEMA);
private static final GoogleCloudDataplexV1Entity entity3 =
new GoogleCloudDataplexV1Entity()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e3")
.setId("e3")
.setSystem(StorageSystem.CLOUD_STORAGE.name())
.setFormat(
new GoogleCloudDataplexV1StorageFormat().setFormat(InputFileFormat.AVRO.name()))
.setDataPath(Resources.getResource(RESOURCES_DIR + "/entity3").getPath())
.setSchema(SCHEMA);
private static final GoogleCloudDataplexV1Entity entity4 =
new GoogleCloudDataplexV1Entity()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/entities/e4")
.setId("e4")
.setSystem(StorageSystem.CLOUD_STORAGE.name())
.setFormat(
new GoogleCloudDataplexV1StorageFormat().setFormat(InputFileFormat.PARQUET.name()))
.setDataPath(Resources.getResource(RESOURCES_DIR + "/entity4").getPath())
.setSchema(SCHEMA);
@Rule public final transient TemporaryFolder temporaryFolder = new TemporaryFolder();
@Rule public final transient TestPipeline mainPipeline = TestPipeline.create();
@Rule public final transient TestPipeline readPipeline = TestPipeline.create();
private GoogleCloudDataplexV1Asset outputAsset;
@Before
public void setup() {
final String tempDir = temporaryFolder.getRoot().getAbsolutePath();
outputAsset =
new GoogleCloudDataplexV1Asset()
.setName("projects/p1/locations/l1/lakes/l1/zones/z1/assets/aout");
outputAsset.setResourceSpec(
new GoogleCloudDataplexV1AssetResourceSpec()
.setType(DataplexAssetResourceSpec.STORAGE_BUCKET.name())
.setName(tempDir));
}
/** Tests CSV to Avro conversion for an entity with partitions. */
@Test
@Category(NeedsRunner.class)
public void testEntityWithPartitionsCsvToAvroE2E() throws IOException {
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getEntities(ImmutableList.of(entity1.getName())))
.thenReturn(ImmutableList.of(entity1));
when(dataplex.getPartitions(entity1.getName()))
.thenReturn(ImmutableList.of(partition11, partition12));
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(entity1.getName());
options.setOutputFileFormat(FileFormatOptions.AVRO);
options.setOutputAsset(outputAsset.getName());
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider);
PCollection<GenericRecord> readAvroFile =
readPipeline.apply(
"ReadAvroFile",
AvroConverters.ReadAvroFile.newBuilder()
.withInputFileSpec(temporaryFolder.getRoot().getAbsolutePath() + "/**/*.avro")
.withSerializedSchema(EXPECT_SERIALIZED_AVRO_SCHEMA)
.build());
PAssert.that(readAvroFile).containsInAnyOrder(EXPECTED_GENERIC_RECORDS);
readPipeline.run();
}
/** Tests JSON to Parquet conversion for an asset with entity using non-default compression. */
@Test
@Category(NeedsRunner.class)
public void testAssetWithEntityJsonToGzippedParquetE2E() throws IOException {
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getCloudStorageEntities(asset2.getName())).thenReturn(ImmutableList.of(entity2));
when(dataplex.getPartitions(entity2.getName())).thenReturn(ImmutableList.of());
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(asset2.getName());
options.setOutputFileFormat(FileFormatOptions.PARQUET);
options.setOutputAsset(outputAsset.getName());
options.setOutputFileCompression(DataplexCompression.GZIP);
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider);
PCollection<GenericRecord> readParquetFile =
readPipeline.apply(
"ReadParquetFile",
ParquetConverters.ReadParquetFile.newBuilder()
.withInputFileSpec(temporaryFolder.getRoot().getAbsolutePath() + "/**/*.parquet")
.withSerializedSchema(EXPECT_SERIALIZED_AVRO_SCHEMA)
.build());
PAssert.that(readParquetFile).containsInAnyOrder(EXPECTED_GENERIC_RECORDS);
readPipeline.run();
}
/** Tests Avro to Parquet conversion for an asset with entity. */
@Test
@Category(NeedsRunner.class)
public void testAssetWithEntityAvroToParquetE2E() throws IOException {
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getEntities(ImmutableList.of(entity3.getName())))
.thenReturn(ImmutableList.of(entity3));
when(dataplex.getPartitions(entity3.getName())).thenReturn(ImmutableList.of());
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(entity3.getName());
options.setOutputFileFormat(FileFormatOptions.PARQUET);
options.setOutputAsset(outputAsset.getName());
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider);
PCollection<GenericRecord> readParquetFile =
readPipeline.apply(
"ReadParquetFile",
ParquetConverters.ReadParquetFile.newBuilder()
.withInputFileSpec(temporaryFolder.getRoot().getAbsolutePath() + "/**/*.parquet")
.withSerializedSchema(EXPECT_SERIALIZED_AVRO_SCHEMA)
.build());
PAssert.that(readParquetFile).containsInAnyOrder(EXPECTED_GENERIC_RECORDS);
readPipeline.run();
}
/** Tests Parquet to Avro conversion for an asset with entity. */
@Test
@Category(NeedsRunner.class)
public void testAssetWithEntityParquetToAvroE2E() throws IOException {
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getEntities(ImmutableList.of(entity4.getName())))
.thenReturn(ImmutableList.of(entity4));
when(dataplex.getPartitions(entity4.getName())).thenReturn(ImmutableList.of());
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(entity4.getName());
options.setOutputFileFormat(FileFormatOptions.AVRO);
options.setOutputAsset(outputAsset.getName());
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider);
PCollection<GenericRecord> readParquetFile =
readPipeline.apply(
"ReadAvroFile",
AvroConverters.ReadAvroFile.newBuilder()
.withInputFileSpec(temporaryFolder.getRoot().getAbsolutePath() + "/**/*.avro")
.withSerializedSchema(EXPECT_SERIALIZED_AVRO_SCHEMA)
.build());
PAssert.that(readParquetFile).containsInAnyOrder(EXPECTED_GENERIC_RECORDS);
readPipeline.run();
}
/**
* Tests JSON to Parquet conversion for an asset with entity when one of the files already exists
* and the existing file behaviour is SKIP.
*/
@Test
@Category(NeedsRunner.class)
public void testAssetWithEntityJsonToParquetSkipExistingFilesE2E() throws IOException {
// setup Dataplex client to return entity 2
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getCloudStorageEntities(asset2.getName())).thenReturn(ImmutableList.of(entity2));
when(dataplex.getPartitions(entity2.getName())).thenReturn(ImmutableList.of());
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
// setup options to skip existing files
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(asset2.getName());
options.setOutputFileFormat(FileFormatOptions.PARQUET);
options.setOutputAsset(outputAsset.getName());
options.setWriteDisposition(WriteDispositionOptions.SKIP);
// simulate the 1.json -> 1.parquet conversion already happened
copyFileToOutputBucket("entity2.existing/1.parquet", "entity2/1.parquet");
// run the pipeline, only 2.json -> 2.parquet conversion should happen
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider);
// read the conversion results
PCollection<GenericRecord> readParquetFile =
readPipeline.apply(
"ReadParquetFile",
ParquetConverters.ReadParquetFile.newBuilder()
.withInputFileSpec(temporaryFolder.getRoot().getAbsolutePath() + "/**/*.parquet")
.withSerializedSchema(EXPECT_SERIALIZED_AVRO_SCHEMA)
.build());
// expect old 1.parquet (from entity2.existing) and newly converted 2.parquet (from entity2)
ImmutableList.Builder<GenericRecord> expected = ImmutableList.builder();
Record record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "abc.existing");
record.put("Number", 1);
expected.add(record);
record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "def");
record.put("Number", 2);
expected.add(record);
record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "ghi");
record.put("Number", 3);
expected.add(record);
PAssert.that(readParquetFile).containsInAnyOrder(expected.build());
readPipeline.run();
}
/**
* Tests JSON to Parquet conversion for an asset with entity when one of the files already exists
* and the existing file behaviour is FAIL.
*/
@Test(expected = RuntimeException.class)
@Category(NeedsRunner.class)
public void testAssetWithEntityJsonToParquetFailOnExistingFilesE2E() throws IOException {
// setup Dataplex client to return entity 2
DataplexClient dataplex = mock(DataplexClient.class);
when(dataplex.getCloudStorageEntities(asset2.getName())).thenReturn(ImmutableList.of(entity2));
when(dataplex.getPartitions(entity2.getName())).thenReturn(ImmutableList.of());
when(dataplex.getAsset(outputAsset.getName())).thenReturn(outputAsset);
// setup options to fail on existing files
FileFormatConversionOptions options =
PipelineOptionsFactory.create().as(FileFormatConversionOptions.class);
options.setInputAssetOrEntitiesList(asset2.getName());
options.setOutputFileFormat(FileFormatOptions.PARQUET);
options.setOutputAsset(outputAsset.getName());
options.setWriteDisposition(WriteDispositionOptions.FAIL);
// simulate the 1.json -> 1.parquet conversion already happened
copyFileToOutputBucket("entity2.existing/1.parquet", "entity2/1.parquet");
// simulate the 2.json -> 2.parquet conversion already happened
copyFileToOutputBucket("entity2.existing/1.parquet", "entity2/2.parquet");
// run the pipeline, the job should fail because 1.parquet already exists
DataplexFileFormatConversion.run(
mainPipeline, options, dataplex, DataplexFileFormatConversionTest::outputPathProvider)
.waitUntilFinish();
}
private void copyFileToOutputBucket(String sourceRelativePath, String destinationRelativePath)
throws IOException {
Path source =
Paths.get(Resources.getResource(RESOURCES_DIR + '/' + sourceRelativePath).getPath());
Path destination =
Paths.get(temporaryFolder.getRoot().getAbsolutePath() + '/' + destinationRelativePath);
Files.createDirectories(destination.getParent());
Files.copy(source, destination);
}
private static ImmutableList<GenericRecord> expectedGenericRecords() {
ImmutableList.Builder<GenericRecord> expected = ImmutableList.builder();
Record record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "abc");
record.put("Number", 1);
expected.add(record);
record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "def");
record.put("Number", 2);
expected.add(record);
record = new Record(EXPECTED_AVRO_SCHEMA);
record.put("Word", "ghi");
record.put("Number", 3);
expected.add(record);
return expected.build();
}
private static String outputPathProvider(String inputPath, String outputBucket) {
String relativeInputPath;
try {
relativeInputPath =
Resources.getResource(RESOURCES_DIR)
.toURI()
.relativize(new File(inputPath).toURI())
.getPath();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
return outputBucket + '/' + relativeInputPath;
}
}