-
Notifications
You must be signed in to change notification settings - Fork 4.6k
Expand file tree
/
Copy pathsnippets_test.py
More file actions
1486 lines (1247 loc) · 53.2 KB
/
snippets_test.py
File metadata and controls
1486 lines (1247 loc) · 53.2 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
# coding=utf-8
#
# 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.
#
"""Tests for all code snippets used in public docs."""
# pytype: skip-file
import gc
import glob
import gzip
import logging
import math
import os
import sys
import tempfile
import time
import unittest
import uuid
import mock
import parameterized
import pytest
import apache_beam as beam
from apache_beam import WindowInto
from apache_beam import coders
from apache_beam import pvalue
from apache_beam import typehints
from apache_beam.coders.coders import ToBytesCoder
from apache_beam.examples.snippets import snippets
from apache_beam.examples.snippets import snippets_examples_wordcount_debugging
from apache_beam.examples.snippets import snippets_examples_wordcount_minimal
from apache_beam.examples.snippets import snippets_examples_wordcount_wordcount
from apache_beam.metrics import Metrics
from apache_beam.metrics.metric import MetricsFilter
from apache_beam.options.pipeline_options import GoogleCloudOptions
from apache_beam.options.pipeline_options import PipelineOptions
from apache_beam.options.pipeline_options import StandardOptions
from apache_beam.testing.test_pipeline import TestPipeline
from apache_beam.testing.test_stream import TestStream
from apache_beam.testing.util import assert_that
from apache_beam.testing.util import equal_to
from apache_beam.transforms import combiners
from apache_beam.transforms.trigger import AccumulationMode
from apache_beam.transforms.trigger import AfterAny
from apache_beam.transforms.trigger import AfterCount
from apache_beam.transforms.trigger import AfterProcessingTime
from apache_beam.transforms.trigger import AfterWatermark
from apache_beam.transforms.trigger import Repeatedly
from apache_beam.transforms.window import FixedWindows
from apache_beam.transforms.window import TimestampedValue
from apache_beam.utils.windowed_value import WindowedValue
# Protect against environments where apitools library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
from apitools.base.py import base_api
except ImportError:
base_api = None
# pylint: enable=wrong-import-order, wrong-import-position
# Protect against environments where datastore library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
from google.cloud.datastore import client as datastore_client
except ImportError:
datastore_client = None
# pylint: enable=wrong-import-order, wrong-import-position
# Protect against environments where the PubSub library is not available.
# pylint: disable=wrong-import-order, wrong-import-position
try:
from google.cloud import pubsub
except ImportError:
pubsub = None
# pylint: enable=wrong-import-order, wrong-import-position
class ParDoTest(unittest.TestCase):
"""Tests for model/par-do."""
def test_pardo(self):
# Note: "words" and "ComputeWordLengthFn" are referenced by name in
# the text of the doc.
words = ['aa', 'bbb', 'c']
# [START model_pardo_pardo]
class ComputeWordLengthFn(beam.DoFn):
def process(self, element):
return [len(element)]
# [END model_pardo_pardo]
# [START model_pardo_apply]
# Apply a ParDo to the PCollection "words" to compute lengths for each word.
word_lengths = words | beam.ParDo(ComputeWordLengthFn())
# [END model_pardo_apply]
self.assertEqual({2, 3, 1}, set(word_lengths))
def test_pardo_yield(self):
words = ['aa', 'bbb', 'c']
# [START model_pardo_yield]
class ComputeWordLengthFn(beam.DoFn):
def process(self, element):
yield len(element)
# [END model_pardo_yield]
word_lengths = words | beam.ParDo(ComputeWordLengthFn())
self.assertEqual({2, 3, 1}, set(word_lengths))
def test_pardo_using_map(self):
words = ['aa', 'bbb', 'c']
# [START model_pardo_using_map]
word_lengths = words | beam.Map(len)
# [END model_pardo_using_map]
self.assertEqual({2, 3, 1}, set(word_lengths))
def test_pardo_using_flatmap(self):
words = ['aa', 'bbb', 'c']
# [START model_pardo_using_flatmap]
word_lengths = words | beam.FlatMap(lambda word: [len(word)])
# [END model_pardo_using_flatmap]
self.assertEqual({2, 3, 1}, set(word_lengths))
def test_pardo_using_flatmap_yield(self):
words = ['aA', 'bbb', 'C']
# [START model_pardo_using_flatmap_yield]
def capitals(word):
for letter in word:
if 'A' <= letter <= 'Z':
yield letter
all_capitals = words | beam.FlatMap(capitals)
# [END model_pardo_using_flatmap_yield]
self.assertEqual({'A', 'C'}, set(all_capitals))
def test_pardo_with_label(self):
words = ['aa', 'bbc', 'defg']
# [START model_pardo_with_label]
result = words | 'CountUniqueLetters' >> beam.Map(
lambda word: len(set(word)))
# [END model_pardo_with_label]
self.assertEqual({1, 2, 4}, set(result))
def test_pardo_side_input(self):
# pylint: disable=line-too-long
with TestPipeline() as p:
words = p | 'start' >> beam.Create(['a', 'bb', 'ccc', 'dddd'])
# [START model_pardo_side_input]
# Callable takes additional arguments.
def filter_using_length(word, lower_bound, upper_bound=float('inf')):
if lower_bound <= len(word) <= upper_bound:
yield word
# Construct a deferred side input.
avg_word_len = (
words
| beam.Map(len)
| beam.CombineGlobally(beam.combiners.MeanCombineFn()))
# Call with explicit side inputs.
small_words = words | 'small' >> beam.FlatMap(filter_using_length, 0, 3)
# A single deferred side input.
larger_than_average = (
words | 'large' >> beam.FlatMap(
filter_using_length, lower_bound=pvalue.AsSingleton(avg_word_len))
)
# Mix and match.
small_but_nontrivial = words | beam.FlatMap(
filter_using_length,
lower_bound=2,
upper_bound=pvalue.AsSingleton(avg_word_len))
# [END model_pardo_side_input]
assert_that(small_words, equal_to(['a', 'bb', 'ccc']))
assert_that(
larger_than_average,
equal_to(['ccc', 'dddd']),
label='larger_than_average')
assert_that(
small_but_nontrivial, equal_to(['bb']), label='small_but_not_trivial')
def test_pardo_side_input_dofn(self):
words = ['a', 'bb', 'ccc', 'dddd']
# [START model_pardo_side_input_dofn]
class FilterUsingLength(beam.DoFn):
def process(self, element, lower_bound, upper_bound=float('inf')):
if lower_bound <= len(element) <= upper_bound:
yield element
small_words = words | beam.ParDo(FilterUsingLength(), 0, 3)
# [END model_pardo_side_input_dofn]
self.assertEqual({'a', 'bb', 'ccc'}, set(small_words))
def test_pardo_with_tagged_outputs(self):
# [START model_pardo_emitting_values_on_tagged_outputs]
class ProcessWords(beam.DoFn):
def process(self, element, cutoff_length, marker):
if len(element) <= cutoff_length:
# Emit this short word to the main output.
yield element
else:
# Emit this word's long length to the 'above_cutoff_lengths' output.
yield pvalue.TaggedOutput('above_cutoff_lengths', len(element))
if element.startswith(marker):
# Emit this word to a different output with the 'marked strings' tag.
yield pvalue.TaggedOutput('marked strings', element)
# [END model_pardo_emitting_values_on_tagged_outputs]
words = ['a', 'an', 'the', 'music', 'xyz']
# [START model_pardo_with_tagged_outputs]
results = (
words
| beam.ParDo(ProcessWords(), cutoff_length=2, marker='x').with_outputs(
'above_cutoff_lengths',
'marked strings',
main='below_cutoff_strings'))
below = results.below_cutoff_strings
above = results.above_cutoff_lengths
marked = results['marked strings'] # indexing works as well
# [END model_pardo_with_tagged_outputs]
self.assertEqual({'a', 'an'}, set(below))
self.assertEqual({3, 5}, set(above))
self.assertEqual({'xyz'}, set(marked))
# [START model_pardo_with_tagged_outputs_iter]
below, above, marked = (words
| beam.ParDo(
ProcessWords(), cutoff_length=2, marker='x')
.with_outputs('above_cutoff_lengths',
'marked strings',
main='below_cutoff_strings'))
# [END model_pardo_with_tagged_outputs_iter]
self.assertEqual({'a', 'an'}, set(below))
self.assertEqual({3, 5}, set(above))
self.assertEqual({'xyz'}, set(marked))
def test_pardo_with_undeclared_outputs(self):
# Note: the use of undeclared outputs is currently not supported in eager
# execution mode.
with TestPipeline() as p:
numbers = p | beam.Create([1, 2, 3, 4, 5, 10, 20])
# [START model_pardo_with_undeclared_outputs]
def even_odd(x):
yield pvalue.TaggedOutput('odd' if x % 2 else 'even', x)
if x % 10 == 0:
yield x
results = numbers | beam.FlatMap(even_odd).with_outputs()
evens = results.even
odds = results.odd
tens = results[None] # the undeclared main output
# [END model_pardo_with_undeclared_outputs]
assert_that(evens, equal_to([2, 4, 10, 20]), label='assert_even')
assert_that(odds, equal_to([1, 3, 5]), label='assert_odds')
assert_that(tens, equal_to([10, 20]), label='assert_tens')
class TypeHintsTest(unittest.TestCase):
def test_bad_types(self):
# [START type_hints_missing_define_numbers]
p = TestPipeline()
numbers = p | beam.Create(['1', '2', '3'])
# [END type_hints_missing_define_numbers]
# Consider the following code.
# pylint: disable=expression-not-assigned
# pylint: disable=unused-variable
# [START type_hints_missing_apply]
evens = numbers | beam.Filter(lambda x: x % 2 == 0)
# [END type_hints_missing_apply]
# Now suppose numbers was defined as [snippet above].
# When running this pipeline, you'd get a runtime error,
# possibly on a remote machine, possibly very late.
with self.assertRaisesRegex(Exception, "not all arguments converted"):
p.run().wait_until_finish()
# To catch this early, we can assert what types we expect.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_takes]
evens = numbers | beam.Filter(lambda x: x % 2 == 0).with_input_types(int)
# [END type_hints_takes]
# Type hints can be declared on DoFns and callables as well, rather
# than where they're used, to be more self contained.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_do_fn]
@beam.typehints.with_input_types(int)
class FilterEvensDoFn(beam.DoFn):
def process(self, element):
if element % 2 == 0:
yield element
evens = numbers | beam.ParDo(FilterEvensDoFn())
# [END type_hints_do_fn]
words = p | 'words' >> beam.Create(['a', 'bb', 'c'])
# One can assert outputs and apply them to transforms as well.
# Helps document the contract and checks it at pipeline construction time.
# [START type_hints_transform]
from typing import Tuple, TypeVar
T = TypeVar('T')
@beam.typehints.with_input_types(T)
@beam.typehints.with_output_types(Tuple[int, T])
class MyTransform(beam.PTransform):
def expand(self, pcoll):
return pcoll | beam.Map(lambda x: (len(x), x))
words_with_lens = words | MyTransform()
# [END type_hints_transform]
# Given an input of str, the inferred output type would be Tuple[int, str].
self.assertEqual(typehints.Tuple[int, str], words_with_lens.element_type)
# pylint: disable=expression-not-assigned
with self.assertRaises(typehints.TypeCheckError):
words_with_lens | beam.Map(lambda x: x).with_input_types(Tuple[int, int])
def test_bad_types_annotations(self):
p = TestPipeline(options=PipelineOptions(pipeline_type_check=True))
numbers = p | beam.Create(['1', '2', '3'])
# Consider the following code.
# pylint: disable=expression-not-assigned
# pylint: disable=unused-variable
class FilterEvensDoFn(beam.DoFn):
def process(self, element):
if element % 2 == 0:
yield element
evens = numbers | 'Untyped Filter' >> beam.ParDo(FilterEvensDoFn())
# Now suppose numbers was defined as [snippet above].
# When running this pipeline, you'd get a runtime error,
# possibly on a remote machine, possibly very late.
with self.assertRaisesRegex(Exception, "not all arguments converted"):
p.run().wait_until_finish()
# To catch this early, we can annotate process() with the expected types.
# Beam will then use these as type hints and perform type checking before
# the pipeline starts.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_do_fn_annotations]
from typing import Iterable
class TypedFilterEvensDoFn(beam.DoFn):
def process(self, element: int) -> Iterable[int]:
if element % 2 == 0:
yield element
evens = numbers | 'filter_evens' >> beam.ParDo(TypedFilterEvensDoFn())
# [END type_hints_do_fn_annotations]
# Another example, using a list output type. Notice that the output
# annotation has an additional Optional for the else clause.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_do_fn_annotations_optional]
from typing import List, Optional
class FilterEvensDoubleDoFn(beam.DoFn):
def process(self, element: int) -> Optional[List[int]]:
if element % 2 == 0:
return [element, element]
return None
evens = numbers | 'double_evens' >> beam.ParDo(FilterEvensDoubleDoFn())
# [END type_hints_do_fn_annotations_optional]
# Example using an annotated function.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_map_annotations]
def my_fn(element: int) -> str:
return 'id_' + str(element)
ids = numbers | 'to_id' >> beam.Map(my_fn)
# [END type_hints_map_annotations]
# Example using an annotated PTransform.
with self.assertRaises(typehints.TypeCheckError):
# [START type_hints_ptransforms]
from apache_beam.pvalue import PCollection
class IntToStr(beam.PTransform):
def expand(self, pcoll: PCollection[int]) -> PCollection[str]:
return pcoll | beam.Map(lambda elem: str(elem))
ids = numbers | 'convert to str' >> IntToStr()
# [END type_hints_ptransforms]
def test_runtime_checks_off(self):
# We do not run the following pipeline, as it has incorrect type
# information, and may fail with obscure errors, depending on the runner
# implementation.
# pylint: disable=expression-not-assigned
# [START type_hints_runtime_off]
p = TestPipeline()
p | beam.Create(['a']) | beam.Map(lambda x: 3).with_output_types(str)
# [END type_hints_runtime_off]
def test_runtime_checks_on(self):
# pylint: disable=expression-not-assigned
with self.assertRaisesRegex(Exception, "According to type-hint"):
# [START type_hints_runtime_on]
p = TestPipeline(options=PipelineOptions(runtime_type_check=True))
p | beam.Create(['a']) | beam.Map(lambda x: 3).with_output_types(str)
result = p.run()
# [END type_hints_runtime_on]
result.wait_until_finish()
def test_deterministic_key(self):
with TestPipeline() as p:
lines = (
p | beam.Create([
'banana,fruit,3',
'kiwi,fruit,2',
'kiwi,fruit,2',
'zucchini,veg,3'
]))
# For pickling.
global Player # pylint: disable=global-variable-not-assigned
# [START type_hints_deterministic_key]
from typing import Tuple
class Player(object):
def __init__(self, team, name):
self.team = team
self.name = name
class PlayerCoder(beam.coders.Coder):
def encode(self, player):
return ('%s:%s' % (player.team, player.name)).encode('utf-8')
def decode(self, s):
return Player(*s.decode('utf-8').split(':'))
def is_deterministic(self):
return True
beam.coders.registry.register_coder(Player, PlayerCoder)
def parse_player_and_score(csv):
name, team, score = csv.split(',')
return Player(team, name), int(score)
totals = (
lines
| beam.Map(parse_player_and_score)
| beam.CombinePerKey(sum).with_input_types(Tuple[Player, int]))
# [END type_hints_deterministic_key]
assert_that(
totals | beam.Map(lambda k_v: (k_v[0].name, k_v[1])),
equal_to([('banana', 3), ('kiwi', 4), ('zucchini', 3)]))
class SnippetsTest(unittest.TestCase):
# Replacing text read/write transforms with dummy transforms for testing.
class DummyReadTransform(beam.PTransform):
"""A transform that will replace iobase.ReadFromText.
To be used for testing.
"""
def __init__(self, file_to_read=None, compression_type=None):
self.file_to_read = file_to_read
self.compression_type = compression_type
class ReadDoFn(beam.DoFn):
def __init__(self, file_to_read, compression_type):
self.file_to_read = file_to_read
self.compression_type = compression_type
self.coder = coders.StrUtf8Coder()
def process(self, element):
pass
def finish_bundle(self):
from apache_beam.transforms import window
assert self.file_to_read
for file_name in glob.glob(self.file_to_read):
if self.compression_type is None:
with open(file_name, 'rb') as file:
for record in file:
value = self.coder.decode(record.rstrip(b'\n'))
yield WindowedValue(value, -1, [window.GlobalWindow()])
else:
with gzip.open(file_name, 'rb') as file:
for record in file:
value = self.coder.decode(record.rstrip(b'\n'))
yield WindowedValue(value, -1, [window.GlobalWindow()])
def expand(self, pcoll):
return pcoll | beam.Create([None]) | 'DummyReadForTesting' >> beam.ParDo(
SnippetsTest.DummyReadTransform.ReadDoFn(
self.file_to_read, self.compression_type))
class DummyWriteTransform(beam.PTransform):
"""A transform that will replace iobase.WriteToText.
To be used for testing.
"""
def __init__(self, file_to_write=None, file_name_suffix=''):
self.file_to_write = file_to_write
class WriteDoFn(beam.DoFn):
def __init__(self, file_to_write):
self.file_to_write = file_to_write
self.file_obj = None
self.coder = ToBytesCoder()
def start_bundle(self):
assert self.file_to_write
# Appending a UUID to create a unique file object per invocation.
self.file_obj = open(self.file_to_write + str(uuid.uuid4()), 'wb')
def process(self, element):
assert self.file_obj
self.file_obj.write(self.coder.encode(element) + b'\n')
def finish_bundle(self):
assert self.file_obj
self.file_obj.close()
def expand(self, pcoll):
return pcoll | 'DummyWriteForTesting' >> beam.ParDo(
SnippetsTest.DummyWriteTransform.WriteDoFn(self.file_to_write))
def setUp(self):
self.old_read_from_text = beam.io.ReadFromText
self.old_write_to_text = beam.io.WriteToText
# Monkey patching to allow testing pipelines defined in snippets.py using
# real data.
beam.io.ReadFromText = SnippetsTest.DummyReadTransform
beam.io.WriteToText = SnippetsTest.DummyWriteTransform
self.temp_files = []
def tearDown(self):
beam.io.ReadFromText = self.old_read_from_text
beam.io.WriteToText = self.old_write_to_text
# Cleanup all the temporary files created in the test.
map(os.remove, self.temp_files)
# Ensure that PipelineOptions subclasses have been cleaned up between tests
gc.collect()
def create_temp_file(self, contents=''):
with tempfile.NamedTemporaryFile(delete=False) as f:
f.write(contents.encode('utf-8'))
self.temp_files.append(f.name)
return f.name
def get_output(self, path, sorted_output=True, suffix=''):
all_lines = []
for file_name in glob.glob(path + '*'):
with open(file_name) as f:
lines = f.readlines()
all_lines.extend([s.rstrip('\n') for s in lines])
if sorted_output:
return sorted(s.rstrip('\n') for s in all_lines)
return all_lines
def test_model_pipelines(self):
temp_path = self.create_temp_file('aa bb cc\n bb cc\n cc')
result_path = temp_path + '.result'
test_argv = [
"unused_argv[0]",
f"--input-file={temp_path}*",
f"--output-path={result_path}",
]
with mock.patch.object(sys, 'argv', test_argv):
snippets.model_pipelines()
self.assertEqual(
self.get_output(result_path),
[str(s) for s in [('aa', 1), ('bb', 2), ('cc', 3)]])
def test_model_pcollection(self):
temp_path = self.create_temp_file()
snippets.model_pcollection(temp_path)
self.assertEqual(
self.get_output(temp_path),
[
'Or to take arms against a sea of troubles, ',
'The slings and arrows of outrageous fortune, ',
'To be, or not to be: that is the question: ',
'Whether \'tis nobler in the mind to suffer ',
])
def test_construct_pipeline(self):
temp_path = self.create_temp_file('abc def ghi\n jkl mno pqr\n stu vwx yz')
result_path = self.create_temp_file()
snippets.construct_pipeline({'read': temp_path, 'write': result_path})
self.assertEqual(
self.get_output(result_path),
['cba', 'fed', 'ihg', 'lkj', 'onm', 'rqp', 'uts', 'xwv', 'zy'])
def test_model_custom_source(self):
snippets.model_custom_source(100)
def test_model_custom_sink(self):
tempdir_name = tempfile.mkdtemp()
class SimpleKV(object):
def __init__(self, tmp_dir):
self._dummy_token = 'dummy_token'
self._tmp_dir = tmp_dir
def connect(self, url):
return self._dummy_token
def open_table(self, access_token, table_name):
assert access_token == self._dummy_token
file_name = self._tmp_dir + os.sep + table_name
assert not os.path.exists(file_name)
open(file_name, 'wb').close()
return table_name
def write_to_table(self, access_token, table_name, key, value):
assert access_token == self._dummy_token
file_name = self._tmp_dir + os.sep + table_name
assert os.path.exists(file_name)
with open(file_name, 'ab') as f:
content = (key + ':' + value + os.linesep).encode('utf-8')
f.write(content)
def rename_table(self, access_token, old_name, new_name):
assert access_token == self._dummy_token
old_file_name = self._tmp_dir + os.sep + old_name
new_file_name = self._tmp_dir + os.sep + new_name
assert os.path.isfile(old_file_name)
assert not os.path.exists(new_file_name)
os.rename(old_file_name, new_file_name)
snippets.model_custom_sink(
SimpleKV(tempdir_name),
[('key' + str(i), 'value' + str(i)) for i in range(100)],
'final_table_no_ptransform',
'final_table_with_ptransform')
expected_output = [
'key' + str(i) + ':' + 'value' + str(i) for i in range(100)
]
glob_pattern = tempdir_name + os.sep + 'final_table_no_ptransform*'
output_files = glob.glob(glob_pattern)
assert output_files
received_output = []
for file_name in output_files:
with open(file_name) as f:
for line in f:
received_output.append(line.rstrip(os.linesep))
self.assertCountEqual(expected_output, received_output)
glob_pattern = tempdir_name + os.sep + 'final_table_with_ptransform*'
output_files = glob.glob(glob_pattern)
assert output_files
received_output = []
for file_name in output_files:
with open(file_name) as f:
for line in f:
received_output.append(line.rstrip(os.linesep))
self.assertCountEqual(expected_output, received_output)
def test_model_textio(self):
temp_path = self.create_temp_file('aa bb cc\n bb cc\n cc')
result_path = temp_path + '.result'
snippets.model_textio({'read': temp_path, 'write': result_path})
self.assertEqual(['aa', 'bb', 'bb', 'cc', 'cc', 'cc'],
self.get_output(result_path, suffix='.csv'))
def test_model_textio_compressed(self):
temp_path = self.create_temp_file('aa\nbb\ncc')
gzip_file_name = temp_path + '.gz'
with open(temp_path, 'rb') as src, gzip.open(gzip_file_name, 'wb') as dst:
dst.writelines(src)
# Add the temporary gzip file to be cleaned up as well.
self.temp_files.append(gzip_file_name)
snippets.model_textio_compressed({'read': gzip_file_name},
['aa', 'bb', 'cc'])
@unittest.skipIf(
datastore_client is None, 'GCP dependencies are not installed')
def test_model_datastoreio(self):
# We cannot test DatastoreIO functionality in unit tests, therefore we limit
# ourselves to making sure the pipeline containing Datastore read and write
# transforms can be built.
# TODO(vikasrk): Expore using Datastore Emulator.
snippets.model_datastoreio()
@unittest.skipIf(base_api is None, 'GCP dependencies are not installed')
def test_model_bigqueryio(self):
# We cannot test BigQueryIO functionality in unit tests, therefore we limit
# ourselves to making sure the pipeline containing BigQuery sources and
# sinks can be built.
#
# To run locally, set `run_locally` to `True`. You will also have to set
# `project`, `dataset` and `table` to the BigQuery table the test will write
# to.
run_locally = False
if run_locally:
project = 'my-project'
dataset = 'samples' # this must already exist
table = 'model_bigqueryio' # this will be created if needed
options = PipelineOptions().view_as(GoogleCloudOptions)
options.project = project
with beam.Pipeline(options=options) as p:
snippets.model_bigqueryio(p, project, dataset, table)
else:
p = TestPipeline()
p.options.view_as(GoogleCloudOptions).temp_location = 'gs://mylocation'
snippets.model_bigqueryio(p)
@pytest.mark.uses_gcp_java_expansion_service
@unittest.skipUnless(
os.environ.get('EXPANSION_PORT'),
"EXPANSION_PORT environment var is not provided.")
def test_model_bigqueryio_xlang(self):
p = TestPipeline()
p.options.view_as(GoogleCloudOptions).temp_location = 'gs://mylocation'
snippets.model_bigqueryio_xlang(p)
def _run_test_pipeline_for_options(self, fn):
temp_path = self.create_temp_file('aa\nbb\ncc')
result_path = temp_path + '.result'
test_argv = [
"unused_argv[0]",
f"--input={temp_path}*",
f"--output={result_path}",
]
with mock.patch.object(sys, 'argv', test_argv):
fn()
self.assertEqual(['aa', 'bb', 'cc'], self.get_output(result_path))
def test_pipeline_options_local(self):
self._run_test_pipeline_for_options(snippets.pipeline_options_local)
def test_pipeline_options_remote(self):
self._run_test_pipeline_for_options(snippets.pipeline_options_remote)
def test_pipeline_options_command_line(self):
self._run_test_pipeline_for_options(snippets.pipeline_options_command_line)
def test_pipeline_logging(self):
result_path = self.create_temp_file()
lines = [
'we found love right where we are',
'we found love right from the start',
'we found love in a hopeless place'
]
snippets.pipeline_logging(lines, result_path)
self.assertEqual(
sorted(' '.join(lines).split(' ')), self.get_output(result_path))
@parameterized.parameterized.expand([
[snippets_examples_wordcount_minimal.examples_wordcount_minimal],
[snippets_examples_wordcount_wordcount.examples_wordcount_wordcount],
[snippets.pipeline_monitoring],
[snippets.examples_wordcount_templated],
])
def test_examples_wordcount(self, pipeline):
temp_path = self.create_temp_file('abc def ghi\n abc jkl')
result_path = self.create_temp_file()
test_argv = [
"unused_argv[0]",
f"--input-file={temp_path}*",
f"--output-path={result_path}",
]
with mock.patch.object(sys, 'argv', test_argv):
pipeline()
self.assertEqual(
self.get_output(result_path), ['abc: 2', 'def: 1', 'ghi: 1', 'jkl: 1'])
def test_examples_ptransforms_templated(self):
pipelines = [snippets.examples_ptransforms_templated]
for pipeline in pipelines:
temp_path = self.create_temp_file('1\n 2\n 3')
result_path = self.create_temp_file()
pipeline({'read': temp_path, 'write': result_path})
self.assertEqual(self.get_output(result_path), ['11', '12', '13'])
def test_examples_wordcount_debugging(self):
temp_path = self.create_temp_file(
'Flourish Flourish Flourish stomach abc def')
result_path = self.create_temp_file()
snippets_examples_wordcount_debugging.examples_wordcount_debugging({
'read': temp_path, 'write': result_path
})
self.assertEqual(
self.get_output(result_path), ['Flourish: 3', 'stomach: 1'])
@unittest.skipIf(pubsub is None, 'GCP dependencies are not installed')
@mock.patch('apache_beam.io.ReadFromPubSub')
@mock.patch('apache_beam.io.WriteToPubSub')
def test_examples_wordcount_streaming(self, *unused_mocks):
def FakeReadFromPubSub(topic=None, subscription=None, values=None):
expected_topic = topic
expected_subscription = subscription
def _inner(topic=None, subscription=None):
assert topic == expected_topic
assert subscription == expected_subscription
return TestStream().add_elements(values)
return _inner
class AssertTransform(beam.PTransform):
def __init__(self, matcher):
self.matcher = matcher
def expand(self, pcoll):
assert_that(pcoll, self.matcher)
def FakeWriteToPubSub(topic=None, values=None):
expected_topic = topic
def _inner(topic=None, subscription=None):
assert topic == expected_topic
return AssertTransform(equal_to(values))
return _inner
# Test basic execution.
input_topic = 'projects/fake-beam-test-project/topic/intopic'
input_values = [
TimestampedValue(b'a a b', 1),
TimestampedValue('🤷 ¯\\_(ツ)_/¯ b b '.encode('utf-8'), 12),
TimestampedValue(b'a b c c c', 20)
]
output_topic = 'projects/fake-beam-test-project/topic/outtopic'
output_values = [b'a: 1', b'a: 2', b'b: 1', b'b: 3', b'c: 3']
beam.io.ReadFromPubSub = (
FakeReadFromPubSub(topic=input_topic, values=input_values))
beam.io.WriteToPubSub = (
FakeWriteToPubSub(topic=output_topic, values=output_values))
test_argv = [
'unused_argv[0]',
'--input_topic',
'projects/fake-beam-test-project/topic/intopic',
'--output_topic',
'projects/fake-beam-test-project/topic/outtopic'
]
with mock.patch.object(sys, 'argv', test_argv):
snippets.examples_wordcount_streaming()
# Test with custom subscription.
input_sub = 'projects/fake-beam-test-project/subscriptions/insub'
beam.io.ReadFromPubSub = FakeReadFromPubSub(
subscription=input_sub, values=input_values)
test_argv = [
'unused_argv[0]',
'--input_subscription',
'projects/fake-beam-test-project/subscriptions/insub',
'--output_topic',
'projects/fake-beam-test-project/topic/outtopic'
]
with mock.patch.object(sys, 'argv', test_argv):
snippets.examples_wordcount_streaming()
def test_model_composite_transform_example(self):
contents = ['aa bb cc', 'bb cc', 'cc']
result_path = self.create_temp_file()
snippets.model_composite_transform_example(contents, result_path)
self.assertEqual(['aa: 1', 'bb: 2', 'cc: 3'], self.get_output(result_path))
def test_model_multiple_pcollections_flatten(self):
contents = ['a', 'b', 'c', 'd', 'e', 'f']
result_path = self.create_temp_file()
snippets.model_multiple_pcollections_flatten(contents, result_path)
self.assertEqual(contents, self.get_output(result_path))
def test_model_multiple_pcollections_flatten_with(self):
contents = ['a', 'b', 'c', 'd', 'e', 'f']
result_path = self.create_temp_file()
snippets.model_multiple_pcollections_flatten_with(contents, result_path)
self.assertEqual(contents, self.get_output(result_path))
def test_model_multiple_pcollections_flatten_with_transform(self):
contents = ['a', 'b', 'c', 'd', 'e', 'f']
result_path = self.create_temp_file()
snippets.model_multiple_pcollections_flatten_with_transform(
contents, result_path)
self.assertEqual(contents + ['x', 'y', 'z'], self.get_output(result_path))
def test_model_multiple_pcollections_partition(self):
contents = [17, 42, 64, 32, 0, 99, 53, 89]
result_path = self.create_temp_file()
snippets.model_multiple_pcollections_partition(contents, result_path)
self.assertEqual(['0', '17', '32', '42', '53', '64', '89', '99'],
self.get_output(result_path))
def test_model_group_by_key(self):
contents = ['a bb ccc bb bb a']
result_path = self.create_temp_file()
snippets.model_group_by_key(contents, result_path)
expected = [('a', 2), ('bb', 3), ('ccc', 1)]
self.assertEqual([str(s) for s in expected], self.get_output(result_path))
def test_model_co_group_by_key_tuple(self):
with TestPipeline() as p:
# [START model_group_by_key_cogroupbykey_tuple_inputs]
emails_list = [
('amy', 'amy@example.com'),
('carl', 'carl@example.com'),
('julia', 'julia@example.com'),
('carl', 'carl@email.com'),
]
phones_list = [
('amy', '111-222-3333'),
('james', '222-333-4444'),
('amy', '333-444-5555'),
('carl', '444-555-6666'),
]
emails = p | 'CreateEmails' >> beam.Create(emails_list)
phones = p | 'CreatePhones' >> beam.Create(phones_list)
# [END model_group_by_key_cogroupbykey_tuple_inputs]
result_path = self.create_temp_file()
snippets.model_co_group_by_key_tuple(emails, phones, result_path)
# [START model_group_by_key_cogroupbykey_tuple_outputs]
results = [
(
'amy',
{
'emails': ['amy@example.com'],
'phones': ['111-222-3333', '333-444-5555']
}),
(
'carl',
{
'emails': ['carl@email.com', 'carl@example.com'],
'phones': ['444-555-6666']
}),
('james', {
'emails': [], 'phones': ['222-333-4444']
}),
('julia', {
'emails': ['julia@example.com'], 'phones': []
}),
]
# [END model_group_by_key_cogroupbykey_tuple_outputs]
# [START model_group_by_key_cogroupbykey_tuple_formatted_outputs]
formatted_results = [
"amy; ['amy@example.com']; ['111-222-3333', '333-444-5555']",
"carl; ['carl@email.com', 'carl@example.com']; ['444-555-6666']",
"james; []; ['222-333-4444']",
"julia; ['julia@example.com']; []",
]
# [END model_group_by_key_cogroupbykey_tuple_formatted_outputs]