github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/coders/observable_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 Observable mixin class."""
    19  # pytype: skip-file
    20  
    21  import logging
    22  import unittest
    23  from typing import List
    24  from typing import Optional
    25  
    26  from apache_beam.coders import observable
    27  
    28  
    29  class ObservableMixinTest(unittest.TestCase):
    30    observed_count = 0
    31    observed_sum = 0
    32    observed_keys = []  # type: List[Optional[str]]
    33  
    34    def observer(self, value, key=None):
    35      self.observed_count += 1
    36      self.observed_sum += value
    37      self.observed_keys.append(key)
    38  
    39    def test_observable(self):
    40      class Watched(observable.ObservableMixin):
    41        def __iter__(self):
    42          for i in (1, 4, 3):
    43            self.notify_observers(i, key='a%d' % i)
    44            yield i
    45  
    46      watched = Watched()
    47      watched.register_observer(lambda v, key: self.observer(v, key=key))
    48      for _ in watched:
    49        pass
    50  
    51      self.assertEqual(3, self.observed_count)
    52      self.assertEqual(8, self.observed_sum)
    53      self.assertEqual(['a1', 'a3', 'a4'], sorted(self.observed_keys))
    54  
    55  
    56  if __name__ == '__main__':
    57    logging.getLogger().setLevel(logging.INFO)
    58    unittest.main()