-
Notifications
You must be signed in to change notification settings - Fork 4.5k
Expand file tree
/
Copy pathyaml_mapping_test.py
More file actions
564 lines (537 loc) · 19.1 KB
/
yaml_mapping_test.py
File metadata and controls
564 lines (537 loc) · 19.1 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
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You 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.
#
import logging
import typing
import unittest
import numpy as np
import apache_beam as beam
from apache_beam import schema_pb2
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.typehints import schemas
from apache_beam.utils.timestamp import Timestamp
from apache_beam.yaml import yaml_mapping
from apache_beam.yaml.yaml_transform import YamlTransform
try:
import jsonschema
except ImportError:
jsonschema = None
DATA = [
beam.Row(label='11a', conductor=11, rank=0),
beam.Row(label='37a', conductor=37, rank=1),
beam.Row(label='389a', conductor=389, rank=2),
]
@unittest.skipIf(jsonschema is None, "Yaml dependencies not installed")
class YamlMappingTest(unittest.TestCase):
def test_basic(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create(DATA)
result = elements | YamlTransform(
'''
type: MapToFields
config:
language: python
fields:
label: label
isogeny: "label[-1]"
''')
assert_that(
result,
equal_to([
beam.Row(label='11a', isogeny='a'),
beam.Row(label='37a', isogeny='a'),
beam.Row(label='389a', isogeny='a'),
]))
def test_drop(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create(DATA)
result = elements | YamlTransform(
'''
type: MapToFields
config:
fields: {}
append: true
drop: [conductor]
''')
assert_that(
result,
equal_to([
beam.Row(label='11a', rank=0),
beam.Row(label='37a', rank=1),
beam.Row(label='389a', rank=2),
]))
def test_filter(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create(DATA)
result = elements | YamlTransform(
'''
type: Filter
config:
language: python
keep: "rank > 0"
''')
assert_that(
result
| beam.Map(lambda named_tuple: beam.Row(**named_tuple._asdict())),
equal_to([
beam.Row(label='37a', conductor=37, rank=1),
beam.Row(label='389a', conductor=389, rank=2),
]))
def test_explode(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(a=2, b='abc', c=.25),
beam.Row(a=3, b='xy', c=.125),
])
result = elements | YamlTransform(
'''
type: chain
transforms:
- type: MapToFields
config:
language: python
append: true
fields:
range: "range(a)"
- type: Explode
config:
fields: [range, b]
cross_product: true
''')
assert_that(
result,
equal_to([
beam.Row(a=2, b='a', c=.25, range=0),
beam.Row(a=2, b='a', c=.25, range=1),
beam.Row(a=2, b='b', c=.25, range=0),
beam.Row(a=2, b='b', c=.25, range=1),
beam.Row(a=2, b='c', c=.25, range=0),
beam.Row(a=2, b='c', c=.25, range=1),
beam.Row(a=3, b='x', c=.125, range=0),
beam.Row(a=3, b='x', c=.125, range=1),
beam.Row(a=3, b='x', c=.125, range=2),
beam.Row(a=3, b='y', c=.125, range=0),
beam.Row(a=3, b='y', c=.125, range=1),
beam.Row(a=3, b='y', c=.125, range=2),
]))
def test_validate(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(key='good', small=[5], nested=beam.Row(big=100)),
beam.Row(key='bad1', small=[500], nested=beam.Row(big=100)),
beam.Row(key='bad2', small=[5], nested=beam.Row(big=1)),
])
result = elements | YamlTransform(
'''
type: ValidateWithSchema
config:
schema:
type: object
properties:
small:
type: array
items:
type: integer
maximum: 10
nested:
type: object
properties:
big:
type: integer
minimum: 10
error_handling:
output: bad
''')
assert_that(
result['good'] | beam.Map(lambda x: x.key), equal_to(['good']))
assert_that(
result['bad'] | beam.Map(lambda x: x.element.key),
equal_to(['bad1', 'bad2']),
label='Errors')
def test_validate_explicit_types(self):
with self.assertRaisesRegex(Exception, r'.*violates schema.*'):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(a=2, b='abc', c=.25),
beam.Row(a=3, b='xy', c=.125),
])
result = elements | YamlTransform(
'''
type: MapToFields
input: input
config:
language: python
fields:
bad:
expression: "a + c"
output_type: string # This is a lie.
''')
self.assertEqual(result.element_type._fields[0][1], str)
def test_partition(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: "'even' if len(element) % 2 == 0 else 'odd'"
language: python
outputs: [even, odd]
''')
self.assertEqual(result['even'].element_type, elements.element_type)
assert_that(
result['even'] | beam.Map(lambda x: x.element),
equal_to(['banana', 'orange']),
label='Even')
assert_that(
result['odd'] | beam.Map(lambda x: x.element),
equal_to(['apple']),
label='Odd')
def test_partition_callable(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by:
callable:
"lambda row: 'even' if len(row.element) % 2 == 0 else 'odd'"
language: python
outputs: [even, odd]
''')
assert_that(
result['even'] | beam.Map(lambda x: x.element),
equal_to(['banana', 'orange']),
label='Even')
assert_that(
result['odd'] | beam.Map(lambda x: x.element),
equal_to(['apple']),
label='Odd')
def test_partition_with_unknown(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: "element.lower()[0]"
language: python
outputs: [a, b, c]
unknown_output: other
''')
assert_that(
result['a'] | beam.Map(lambda x: x.element),
equal_to(['apple']),
label='A')
assert_that(
result['b'] | beam.Map(lambda x: x.element),
equal_to(['banana']),
label='B')
assert_that(
result['c'] | beam.Map(lambda x: x.element), equal_to([]), label='C')
assert_that(
result['other'] | beam.Map(lambda x: x.element),
equal_to(['orange']),
label='Other')
def test_partition_without_unknown(self):
with self.assertRaisesRegex(Exception, r'.*Unknown output name.*"o".*'):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
_ = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: "element.lower()[0]"
language: python
outputs: [a, b, c]
''')
def test_partition_without_unknown_with_error(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: "element.lower()[0]"
language: python
outputs: [a, b, c]
error_handling:
output: unknown
''')
assert_that(
result['a'] | beam.Map(lambda x: x.element),
equal_to(['apple']),
label='A')
assert_that(
result['b'] | beam.Map(lambda x: x.element),
equal_to(['banana']),
label='B')
assert_that(
result['c'] | beam.Map(lambda x: x.element), equal_to([]), label='C')
assert_that(
result['unknown'] | beam.Map(lambda x: x.element.element),
equal_to(['orange']),
label='Errors')
def test_partition_with_actual_error(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple'),
beam.Row(element='banana'),
beam.Row(element='orange'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: "element.lower()[5]"
language: python
outputs: [a, b, c]
unknown_output: other
error_handling:
output: errors
''')
assert_that(
result['a'] | beam.Map(lambda x: x.element),
equal_to(['banana']),
label='B')
assert_that(
result['other'] | beam.Map(lambda x: x.element),
equal_to(['orange']),
label='Other')
# Apple only has 5 letters, resulting in an index error.
assert_that(
result['errors'] | beam.Map(lambda x: x.element.element),
equal_to(['apple']),
label='Errors')
def test_partition_no_language(self):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple', texture='smooth'),
beam.Row(element='banana', texture='smooth'),
beam.Row(element='orange', texture='bumpy'),
])
result = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: texture
outputs: [bumpy, smooth]
''')
assert_that(
result['bumpy'] | beam.Map(lambda x: x.element),
equal_to(['orange']),
label='Bumpy')
assert_that(
result['smooth'] | beam.Map(lambda x: x.element),
equal_to(['apple', 'banana']),
label='Smooth')
def test_partition_bad_static_type(self):
with self.assertRaisesRegex(
ValueError, r'.*Partition function .*must return a string.*'):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple', texture='smooth'),
beam.Row(element='banana', texture='smooth'),
beam.Row(element='orange', texture='bumpy'),
])
_ = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: len(texture)
outputs: [bumpy, smooth]
language: python
''')
def test_partition_bad_runtime_type(self):
with self.assertRaisesRegex(Exception,
r'Returned output name.*must be a string.*'):
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = p | beam.Create([
beam.Row(element='apple', texture='smooth'),
beam.Row(element='banana', texture='smooth'),
beam.Row(element='orange', texture='bumpy'),
])
_ = elements | YamlTransform(
'''
type: Partition
input: input
config:
by: print(texture)
outputs: [bumpy, smooth]
language: python
''')
def test_append_type_inference(self):
p = beam.Pipeline(
options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle'))
elements = p | beam.Create(DATA)
elements.element_type = schemas.named_tuple_from_schema(
schema_pb2.Schema(
fields=[
schemas.schema_field('label', str),
schemas.schema_field('conductor', int),
schemas.schema_field('rank', int)
]))
result = elements | YamlTransform(
'''
type: MapToFields
config:
language: python
append: true
fields:
new_label: label
''')
self.assertSequenceEqual(
result.element_type._fields,
(('label', str), ('conductor', np.int64), ('rank', np.int64),
('new_label', str)))
def test_extract_windowing_info(self):
T = typing.TypeVar('T')
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = (
p
| beam.Create(
[beam.Row(value=1), beam.Row(value=2), beam.Row(value=11)])
| beam.Map(
lambda x: beam.transforms.window.TimestampedValue(
x, timestamp=x.value)).with_input_types(T).with_output_types(
T)
| beam.WindowInto(beam.transforms.window.FixedWindows(10)))
result = elements | YamlTransform(
'''
type: ExtractWindowingInfo
config:
fields:
timestamp: timestamp
window_start: window_start
window_end: window_end
window_string: window_string
window_type: window_type
window_object: window_object
pane_info_field: pane_info
''')
assert_that(
result,
equal_to([
beam.Row(
value=1,
timestamp=Timestamp(1),
window_start=Timestamp(0),
window_end=Timestamp(10),
window_string='[0.0, 10.0)',
window_type='IntervalWindow',
window_object=beam.transforms.window.IntervalWindow(0, 10),
pane_info_field=yaml_mapping.PaneInfoTuple(
True, True, 'UNKNOWN', 0, 0)),
beam.Row(
value=2,
timestamp=Timestamp(2),
window_start=Timestamp(0),
window_end=Timestamp(10),
window_string='[0.0, 10.0)',
window_type='IntervalWindow',
window_object=beam.transforms.window.IntervalWindow(0, 10),
pane_info_field=yaml_mapping.PaneInfoTuple(
True, True, 'UNKNOWN', 0, 0)),
beam.Row(
value=11,
timestamp=Timestamp(11),
window_start=Timestamp(10),
window_end=Timestamp(20),
window_string='[10.0, 20.0)',
window_type='IntervalWindow',
window_object=beam.transforms.window.IntervalWindow(10, 20),
pane_info_field=yaml_mapping.PaneInfoTuple(
True, True, 'UNKNOWN', 0, 0)),
]))
def test_extract_windowing_info_iterable(self):
T = typing.TypeVar('T')
with beam.Pipeline(options=beam.options.pipeline_options.PipelineOptions(
pickle_library='cloudpickle')) as p:
elements = (
p
| beam.Create(
[beam.Row(value=1), beam.Row(value=2), beam.Row(value=11)])
| beam.Map(
lambda x: beam.transforms.window.TimestampedValue(
x, timestamp=x.value)).with_input_types(T).with_output_types(
T))
result = elements | YamlTransform(
'''
type: ExtractWindowingInfo
config:
fields: [timestamp, window_type]
''')
assert_that(
result,
equal_to([
beam.Row(
value=1, timestamp=Timestamp(1), window_type='GlobalWindow'),
beam.Row(
value=2, timestamp=Timestamp(2), window_type='GlobalWindow'),
beam.Row(
value=11, timestamp=Timestamp(11),
window_type='GlobalWindow'),
]))
if __name__ == '__main__':
logging.getLogger().setLevel(logging.INFO)
unittest.main()