|
| 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 | +"""Runs integration tests in the tests directory.""" |
| 19 | + |
| 20 | +import argparse |
| 21 | +import contextlib |
| 22 | +import copy |
| 23 | +import glob |
| 24 | +import itertools |
| 25 | +import logging |
| 26 | +import mock |
| 27 | +import os |
| 28 | +import random |
| 29 | +import re |
| 30 | +import sys |
| 31 | +import tempfile |
| 32 | +import uuid |
| 33 | +import unittest |
| 34 | + |
| 35 | +import yaml |
| 36 | +from yaml.loader import SafeLoader |
| 37 | + |
| 38 | +import apache_beam as beam |
| 39 | +from apache_beam.io import filesystems |
| 40 | +from apache_beam.options.pipeline_options import PipelineOptions |
| 41 | +from apache_beam.typehints import trivial_inference |
| 42 | +from apache_beam.yaml import yaml_mapping |
| 43 | +from apache_beam.yaml import yaml_provider |
| 44 | +from apache_beam.yaml import yaml_transform |
| 45 | + |
| 46 | +from apache_beam.utils import python_callable |
| 47 | + |
| 48 | + |
| 49 | +@contextlib.contextmanager |
| 50 | +def gcs_temp_dir(bucket): |
| 51 | + gcs_tempdir = bucket + '/yaml-' + str(uuid.uuid4()) |
| 52 | + yield gcs_tempdir |
| 53 | + filesystems.FileSystems.delete([gcs_tempdir]) |
| 54 | + |
| 55 | + |
| 56 | +def replace_recursive(spec, vars): |
| 57 | + if isinstance(spec, dict): |
| 58 | + return { |
| 59 | + key: replace_recursive(value, vars) |
| 60 | + for (key, value) in spec.items() |
| 61 | + } |
| 62 | + elif isinstance(spec, list): |
| 63 | + return [replace_recursive(value, vars) for value in spec] |
| 64 | + elif isinstance(spec, str) and '{' in spec: |
| 65 | + try: |
| 66 | + return eval('f' + repr(spec), vars) |
| 67 | + except Exception as exn: |
| 68 | + raise ValueError(f"Error evaluating {spec}: {exn}") from exn |
| 69 | + else: |
| 70 | + return spec |
| 71 | + |
| 72 | + |
| 73 | +def transform_types(spec): |
| 74 | + if spec.get('type', None) in (None, 'composite', 'chain'): |
| 75 | + if 'source' in spec: |
| 76 | + yield from transform_types(spec['source']) |
| 77 | + for t in spec.get('transforms', []): |
| 78 | + yield from transform_types(t) |
| 79 | + if 'sink' in spec: |
| 80 | + yield from transform_types(spec['sink']) |
| 81 | + else: |
| 82 | + yield spec['type'] |
| 83 | + |
| 84 | + |
| 85 | +def provider_sets(spec, require_available=False): |
| 86 | + """For transforms that are vended by multiple providers, yields all possible |
| 87 | + combinations of providers to use. |
| 88 | + """ |
| 89 | + all_transform_types = set.union( |
| 90 | + *( |
| 91 | + set( |
| 92 | + transform_types( |
| 93 | + yaml_transform.preprocess(copy.deepcopy(p['pipeline'])))) |
| 94 | + for p in spec['pipelines'])) |
| 95 | + |
| 96 | + def filter_to_available(t, providers): |
| 97 | + if require_available: |
| 98 | + for p in providers: |
| 99 | + if not p.available(): |
| 100 | + raise ValueError("Provider {p} required for {t} is not available.") |
| 101 | + return providers |
| 102 | + else: |
| 103 | + return [p for p in providers if p.available()] |
| 104 | + |
| 105 | + standard_providers = yaml_provider.standard_providers() |
| 106 | + multiple_providers = { |
| 107 | + t: filter_to_available(t, standard_providers[t]) |
| 108 | + for t in all_transform_types |
| 109 | + if len(filter_to_available(t, standard_providers[t])) > 1 |
| 110 | + } |
| 111 | + if not multiple_providers: |
| 112 | + return None, standard_providers |
| 113 | + else: |
| 114 | + names, provider_lists = zip(*sorted(multiple_providers.items())) |
| 115 | + for ix, c in enumerate(itertools.product(*provider_lists)): |
| 116 | + yield ( |
| 117 | + '_'.join( |
| 118 | + n + '_' + type(p.underlying_provider()).__name__ |
| 119 | + for (n, p) in zip(names, c)) + f'_{ix}', |
| 120 | + dict(standard_providers, **{n: [p] |
| 121 | + for (n, p) in zip(names, c)})) |
| 122 | + |
| 123 | + |
| 124 | +def create_test_methods(spec): |
| 125 | + for suffix, providers in provider_sets(spec): |
| 126 | + |
| 127 | + def test(self, providers=providers): # default arg to capture loop value |
| 128 | + vars = {} |
| 129 | + with contextlib.ExitStack() as stack: |
| 130 | + stack.enter_context( |
| 131 | + mock.patch( |
| 132 | + 'apache_beam.yaml.yaml_provider.standard_providers', |
| 133 | + lambda: providers)) |
| 134 | + for fixture in spec.get('fixtures', []): |
| 135 | + vars[fixture['name']] = stack.enter_context( |
| 136 | + python_callable.PythonCallableWithSource. |
| 137 | + load_from_fully_qualified_name(fixture['type'])( |
| 138 | + **yaml_transform.SafeLineLoader.strip_metadata( |
| 139 | + fixture.get('config', {})))) |
| 140 | + for pipeline_spec in spec['pipelines']: |
| 141 | + with beam.Pipeline(options=PipelineOptions( |
| 142 | + pickle_library='cloudpickle', |
| 143 | + **yaml_transform.SafeLineLoader.strip_metadata(pipeline_spec.get( |
| 144 | + 'options', {})))) as p: |
| 145 | + yaml_transform.expand_pipeline( |
| 146 | + p, replace_recursive(pipeline_spec, vars)) |
| 147 | + |
| 148 | + yield suffix, test |
| 149 | + |
| 150 | + |
| 151 | +def parse_test_files(filepattern): |
| 152 | + for path in glob.glob(filepattern): |
| 153 | + with open(path) as fin: |
| 154 | + base_name = f'test_{os.path.basename(path)}'.replace('.', '_') |
| 155 | + for suffix, func in create_test_methods( |
| 156 | + yaml.load(fin, Loader=yaml_transform.SafeLineLoader)): |
| 157 | + if suffix: |
| 158 | + yield f'{base_name}_{suffix}', func |
| 159 | + else: |
| 160 | + yield base_name, func |
| 161 | + |
| 162 | + |
| 163 | +def createTestSuite(name, filepattern): |
| 164 | + return type(name, (unittest.TestCase, ), dict(parse_test_files(filepattern))) |
| 165 | + |
| 166 | + |
| 167 | +IntegrationTests = createTestSuite( |
| 168 | + 'IntegrationTests', |
| 169 | + os.path.join(os.path.dirname(__file__), 'tests', '*.yaml')) |
| 170 | + |
| 171 | +if __name__ == '__main__': |
| 172 | + logging.getLogger().setLevel(logging.INFO) |
| 173 | + unittest.main(argv=unknown_args) |
0 commit comments