github.com/apache/beam/sdks/v2@v2.48.2/python/apache_beam/examples/snippets/util.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  # pytype: skip-file
    19  
    20  import ast
    21  import shlex
    22  import subprocess as sp
    23  
    24  import apache_beam as beam
    25  from apache_beam.testing.util import assert_that
    26  from apache_beam.testing.util import equal_to
    27  
    28  
    29  def assert_matches_stdout(
    30      actual, expected_stdout, normalize_fn=lambda elem: elem, label=''):
    31    """Asserts a PCollection of strings matches the expected stdout elements.
    32  
    33    Args:
    34      actual (beam.PCollection): A PCollection.
    35      expected (List[str]): A list of stdout elements, one line per element.
    36      normalize_fn (Function[any]): A function to normalize elements before
    37          comparing them. Can be used to sort lists before comparing.
    38      label (str): [optional] Label to make transform names unique.
    39    """
    40    def stdout_to_python_object(elem_str):
    41      try:
    42        elem = ast.literal_eval(elem_str)
    43      except (SyntaxError, ValueError):
    44        elem = elem_str
    45      return normalize_fn(elem)
    46  
    47    actual = actual | label >> beam.Map(stdout_to_python_object)
    48    expected = list(map(stdout_to_python_object, expected_stdout))
    49    assert_that(actual, equal_to(expected), 'assert ' + label)
    50  
    51  
    52  def run_shell_commands(commands, **kwargs):
    53    """Runs a list of Notebook-like shell commands.
    54  
    55    Lines starting with `#` are ignored as comments.
    56    Lines starting with `!` are run as commands.
    57    Variables like `{variable}` are substituted with **kwargs.
    58    """
    59    for cmd in commands:
    60      cmd = cmd.strip().lstrip('!').format(**kwargs)
    61      sp_cmd = shlex.split(cmd, comments=True, posix=True)
    62      if sp_cmd:
    63        sp.call(sp_cmd)
    64        yield sp_cmd