github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/examples/cookbook/custom_ptransform_test.py (about)

     1  #
     2  # Licensed to the Apache Software Foundation (ASF) under one or more
     3  # contributor license agreements.  See the NOTICE file distributed with
     4  # this work for additional information regarding copyright ownership.
     5  # The ASF licenses this file to You under the Apache License, Version 2.0
     6  # (the "License"); you may not use this file except in compliance with
     7  # the License.  You may obtain a copy of the License at
     8  #
     9  #    http://www.apache.org/licenses/LICENSE-2.0
    10  #
    11  # Unless required by applicable law or agreed to in writing, software
    12  # distributed under the License is distributed on an "AS IS" BASIS,
    13  # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    14  # See the License for the specific language governing permissions and
    15  # limitations under the License.
    16  #
    17  
    18  """Tests for the various custom Count implementation examples."""
    19  
    20  # pytype: skip-file
    21  
    22  import logging
    23  import unittest
    24  
    25  import apache_beam as beam
    26  from apache_beam.examples.cookbook import custom_ptransform
    27  from apache_beam.testing.test_pipeline import TestPipeline
    28  from apache_beam.testing.util import assert_that
    29  from apache_beam.testing.util import equal_to
    30  
    31  
    32  class CustomCountTest(unittest.TestCase):
    33    WORDS = ['CAT', 'DOG', 'CAT', 'CAT', 'DOG']
    34  
    35    def create_content_input_file(self, path, contents):
    36      logging.info('Creating temp file: %s', path)
    37      with open(path, 'w') as f:
    38        f.write(contents)
    39  
    40    def test_count1(self):
    41      self.run_pipeline(custom_ptransform.Count1())
    42  
    43    def test_count2(self):
    44      self.run_pipeline(custom_ptransform.Count2())
    45  
    46    def test_count3(self):
    47      factor = 2
    48      self.run_pipeline(custom_ptransform.Count3(factor), factor=factor)
    49  
    50    def run_pipeline(self, count_implementation, factor=1):
    51      with TestPipeline() as p:
    52        words = p | beam.Create(self.WORDS)
    53        result = words | count_implementation
    54        assert_that(
    55            result, equal_to([('CAT', (3 * factor)), ('DOG', (2 * factor))]))
    56  
    57  
    58  if __name__ == '__main__':
    59    logging.getLogger().setLevel(logging.INFO)
    60    unittest.main()