blob: 7d3d20d8a45008865b380eadfc149b8a3921ceb6 [file] [log] [blame]
Jamie Madillcf4f8c72021-05-20 19:24:231#!/usr/bin/env python3
Kenneth Russelleb60cbd22017-12-05 07:54:282# Copyright 2016 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Script to generate the majority of the JSON files in the src/testing/buildbot
7directory. Maintaining these files by hand is too unwieldy.
8"""
9
10import argparse
11import ast
12import collections
13import copy
John Budorick826d5ed2017-12-28 19:27:3214import difflib
Jamie Madillcf4f8c72021-05-20 19:24:2315import functools
Garrett Beatyd5ca75962020-05-07 16:58:3116import glob
Kenneth Russell8ceeabf2017-12-11 17:53:2817import itertools
Kenneth Russelleb60cbd22017-12-05 07:54:2818import json
19import os
Greg Gutermanf60eb052020-03-12 17:40:0120import re
Kenneth Russelleb60cbd22017-12-05 07:54:2821import string
22import sys
John Budorick826d5ed2017-12-28 19:27:3223import traceback
Kenneth Russelleb60cbd22017-12-05 07:54:2824
Brian Sheedya31578e2020-05-18 20:24:3625import buildbot_json_magic_substitutions as magic_substitutions
26
Kenneth Russelleb60cbd22017-12-05 07:54:2827THIS_DIR = os.path.dirname(os.path.abspath(__file__))
28
Brian Sheedyf74819b2021-06-04 01:38:3829BROWSER_CONFIG_TO_TARGET_SUFFIX_MAP = {
30 'android-chromium': '_android_chrome',
31 'android-chromium-monochrome': '_android_monochrome',
32 'android-weblayer': '_android_weblayer',
33 'android-webview': '_android_webview',
34}
35
Kenneth Russelleb60cbd22017-12-05 07:54:2836
37class BBGenErr(Exception):
Nico Weber79dc5f6852018-07-13 19:38:4938 def __init__(self, message):
39 super(BBGenErr, self).__init__(message)
Kenneth Russelleb60cbd22017-12-05 07:54:2840
41
Kenneth Russell8ceeabf2017-12-11 17:53:2842# This class is only present to accommodate certain machines on
43# chromium.android.fyi which run certain tests as instrumentation
44# tests, but not as gtests. If this discrepancy were fixed then the
45# notion could be removed.
46class TestSuiteTypes(object):
47 GTEST = 'gtest'
48
49
Kenneth Russelleb60cbd22017-12-05 07:54:2850class BaseGenerator(object):
51 def __init__(self, bb_gen):
52 self.bb_gen = bb_gen
53
Kenneth Russell8ceeabf2017-12-11 17:53:2854 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:2855 raise NotImplementedError()
56
57 def sort(self, tests):
58 raise NotImplementedError()
59
60
Jamie Madillcf4f8c72021-05-20 19:24:2361def custom_cmp(a, b):
62 return int(a > b) - int(a < b)
63
64
Kenneth Russell8ceeabf2017-12-11 17:53:2865def cmp_tests(a, b):
66 # Prefer to compare based on the "test" key.
Jamie Madillcf4f8c72021-05-20 19:24:2367 val = custom_cmp(a['test'], b['test'])
Kenneth Russell8ceeabf2017-12-11 17:53:2868 if val != 0:
69 return val
70 if 'name' in a and 'name' in b:
Jamie Madillcf4f8c72021-05-20 19:24:2371 return custom_cmp(a['name'], b['name']) # pragma: no cover
Kenneth Russell8ceeabf2017-12-11 17:53:2872 if 'name' not in a and 'name' not in b:
73 return 0 # pragma: no cover
74 # Prefer to put variants of the same test after the first one.
75 if 'name' in a:
76 return 1
77 # 'name' is in b.
78 return -1 # pragma: no cover
79
80
Kenneth Russell8a386d42018-06-02 09:48:0181class GPUTelemetryTestGenerator(BaseGenerator):
Bo Liu555a0f92019-03-29 12:11:5682
83 def __init__(self, bb_gen, is_android_webview=False):
Kenneth Russell8a386d42018-06-02 09:48:0184 super(GPUTelemetryTestGenerator, self).__init__(bb_gen)
Bo Liu555a0f92019-03-29 12:11:5685 self._is_android_webview = is_android_webview
Kenneth Russell8a386d42018-06-02 09:48:0186
87 def generate(self, waterfall, tester_name, tester_config, input_tests):
88 isolated_scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:2389 for test_name, test_config in sorted(input_tests.items()):
Kenneth Russell8a386d42018-06-02 09:48:0190 test = self.bb_gen.generate_gpu_telemetry_test(
Bo Liu555a0f92019-03-29 12:11:5691 waterfall, tester_name, tester_config, test_name, test_config,
92 self._is_android_webview)
Kenneth Russell8a386d42018-06-02 09:48:0193 if test:
94 isolated_scripts.append(test)
95 return isolated_scripts
96
97 def sort(self, tests):
98 return sorted(tests, key=lambda x: x['name'])
99
100
Kenneth Russelleb60cbd22017-12-05 07:54:28101class GTestGenerator(BaseGenerator):
102 def __init__(self, bb_gen):
103 super(GTestGenerator, self).__init__(bb_gen)
104
Kenneth Russell8ceeabf2017-12-11 17:53:28105 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28106 # The relative ordering of some of the tests is important to
107 # minimize differences compared to the handwritten JSON files, since
108 # Python's sorts are stable and there are some tests with the same
109 # key (see gles2_conform_d3d9_test and similar variants). Avoid
110 # losing the order by avoiding coalescing the dictionaries into one.
111 gtests = []
Jamie Madillcf4f8c72021-05-20 19:24:23112 for test_name, test_config in sorted(input_tests.items()):
Jeff Yoon67c3e832020-02-08 07:39:38113 # Variants allow more than one definition for a given test, and is defined
114 # in array format from resolve_variants().
115 if not isinstance(test_config, list):
116 test_config = [test_config]
117
118 for config in test_config:
119 test = self.bb_gen.generate_gtest(
120 waterfall, tester_name, tester_config, test_name, config)
121 if test:
122 # generate_gtest may veto the test generation on this tester.
123 gtests.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28124 return gtests
125
126 def sort(self, tests):
Jamie Madillcf4f8c72021-05-20 19:24:23127 return sorted(tests, key=functools.cmp_to_key(cmp_tests))
Kenneth Russelleb60cbd22017-12-05 07:54:28128
129
130class IsolatedScriptTestGenerator(BaseGenerator):
131 def __init__(self, bb_gen):
132 super(IsolatedScriptTestGenerator, self).__init__(bb_gen)
133
Kenneth Russell8ceeabf2017-12-11 17:53:28134 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28135 isolated_scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23136 for test_name, test_config in sorted(input_tests.items()):
Jeff Yoonb8bfdbf32020-03-13 19:14:43137 # Variants allow more than one definition for a given test, and is defined
138 # in array format from resolve_variants().
139 if not isinstance(test_config, list):
140 test_config = [test_config]
141
142 for config in test_config:
143 test = self.bb_gen.generate_isolated_script_test(
144 waterfall, tester_name, tester_config, test_name, config)
145 if test:
146 isolated_scripts.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28147 return isolated_scripts
148
149 def sort(self, tests):
150 return sorted(tests, key=lambda x: x['name'])
151
152
153class ScriptGenerator(BaseGenerator):
154 def __init__(self, bb_gen):
155 super(ScriptGenerator, self).__init__(bb_gen)
156
Kenneth Russell8ceeabf2017-12-11 17:53:28157 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28158 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23159 for test_name, test_config in sorted(input_tests.items()):
Kenneth Russelleb60cbd22017-12-05 07:54:28160 test = self.bb_gen.generate_script_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28161 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28162 if test:
163 scripts.append(test)
164 return scripts
165
166 def sort(self, tests):
167 return sorted(tests, key=lambda x: x['name'])
168
169
170class JUnitGenerator(BaseGenerator):
171 def __init__(self, bb_gen):
172 super(JUnitGenerator, self).__init__(bb_gen)
173
Kenneth Russell8ceeabf2017-12-11 17:53:28174 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28175 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23176 for test_name, test_config in sorted(input_tests.items()):
Kenneth Russelleb60cbd22017-12-05 07:54:28177 test = self.bb_gen.generate_junit_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28178 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28179 if test:
180 scripts.append(test)
181 return scripts
182
183 def sort(self, tests):
184 return sorted(tests, key=lambda x: x['test'])
185
186
Xinan Lin05fb9c1752020-12-17 00:15:52187class SkylabGenerator(BaseGenerator):
188 def __init__(self, bb_gen):
189 super(SkylabGenerator, self).__init__(bb_gen)
190
191 def generate(self, waterfall, tester_name, tester_config, input_tests):
192 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23193 for test_name, test_config in sorted(input_tests.items()):
Xinan Lin05fb9c1752020-12-17 00:15:52194 for config in test_config:
195 test = self.bb_gen.generate_skylab_test(waterfall, tester_name,
196 tester_config, test_name,
197 config)
198 if test:
199 scripts.append(test)
200 return scripts
201
202 def sort(self, tests):
203 return sorted(tests, key=lambda x: x['test'])
204
205
Jeff Yoon67c3e832020-02-08 07:39:38206def check_compound_references(other_test_suites=None,
207 sub_suite=None,
208 suite=None,
209 target_test_suites=None,
210 test_type=None,
211 **kwargs):
212 """Ensure comound reference's don't target other compounds"""
213 del kwargs
214 if sub_suite in other_test_suites or sub_suite in target_test_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15215 raise BBGenErr('%s may not refer to other composition type test '
216 'suites (error found while processing %s)' %
217 (test_type, suite))
218
Jeff Yoon67c3e832020-02-08 07:39:38219
220def check_basic_references(basic_suites=None,
221 sub_suite=None,
222 suite=None,
223 **kwargs):
224 """Ensure test has a basic suite reference"""
225 del kwargs
226 if sub_suite not in basic_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15227 raise BBGenErr('Unable to find reference to %s while processing %s' %
228 (sub_suite, suite))
229
Jeff Yoon67c3e832020-02-08 07:39:38230
231def check_conflicting_definitions(basic_suites=None,
232 seen_tests=None,
233 sub_suite=None,
234 suite=None,
235 test_type=None,
236 **kwargs):
237 """Ensure that if a test is reachable via multiple basic suites,
238 all of them have an identical definition of the tests.
239 """
240 del kwargs
241 for test_name in basic_suites[sub_suite]:
242 if (test_name in seen_tests and
243 basic_suites[sub_suite][test_name] !=
244 basic_suites[seen_tests[test_name]][test_name]):
245 raise BBGenErr('Conflicting test definitions for %s from %s '
246 'and %s in %s (error found while processing %s)'
247 % (test_name, seen_tests[test_name], sub_suite,
248 test_type, suite))
249 seen_tests[test_name] = sub_suite
250
251def check_matrix_identifier(sub_suite=None,
252 suite=None,
253 suite_def=None,
Jeff Yoonda581c32020-03-06 03:56:05254 all_variants=None,
Jeff Yoon67c3e832020-02-08 07:39:38255 **kwargs):
256 """Ensure 'idenfitier' is defined for each variant"""
257 del kwargs
258 sub_suite_config = suite_def[sub_suite]
259 for variant in sub_suite_config.get('variants', []):
Jeff Yoonda581c32020-03-06 03:56:05260 if isinstance(variant, str):
261 if variant not in all_variants:
262 raise BBGenErr('Missing variant definition for %s in variants.pyl'
263 % variant)
264 variant = all_variants[variant]
265
Jeff Yoon67c3e832020-02-08 07:39:38266 if not 'identifier' in variant:
267 raise BBGenErr('Missing required identifier field in matrix '
268 'compound suite %s, %s' % (suite, sub_suite))
269
270
Kenneth Russelleb60cbd22017-12-05 07:54:28271class BBJSONGenerator(object):
Garrett Beaty1afaccc2020-06-25 19:58:15272 def __init__(self, args):
Kenneth Russelleb60cbd22017-12-05 07:54:28273 self.this_dir = THIS_DIR
Garrett Beaty1afaccc2020-06-25 19:58:15274 self.args = args
Kenneth Russelleb60cbd22017-12-05 07:54:28275 self.waterfalls = None
276 self.test_suites = None
277 self.exceptions = None
Stephen Martinisb72f6d22018-10-04 23:29:01278 self.mixins = None
Nodir Turakulovfce34292019-12-18 17:05:41279 self.gn_isolate_map = None
Jeff Yoonda581c32020-03-06 03:56:05280 self.variants = None
Kenneth Russelleb60cbd22017-12-05 07:54:28281
Garrett Beaty1afaccc2020-06-25 19:58:15282 @staticmethod
283 def parse_args(argv):
284
285 # RawTextHelpFormatter allows for styling of help statement
286 parser = argparse.ArgumentParser(
287 formatter_class=argparse.RawTextHelpFormatter)
288
289 group = parser.add_mutually_exclusive_group()
290 group.add_argument(
291 '-c',
292 '--check',
293 action='store_true',
294 help=
295 'Do consistency checks of configuration and generated files and then '
296 'exit. Used during presubmit. '
297 'Causes the tool to not generate any files.')
298 group.add_argument(
299 '--query',
300 type=str,
301 help=(
302 "Returns raw JSON information of buildbots and tests.\n" +
303 "Examples:\n" + " List all bots (all info):\n" +
304 " --query bots\n\n" +
305 " List all bots and only their associated tests:\n" +
306 " --query bots/tests\n\n" +
307 " List all information about 'bot1' " +
308 "(make sure you have quotes):\n" + " --query bot/'bot1'\n\n" +
309 " List tests running for 'bot1' (make sure you have quotes):\n" +
310 " --query bot/'bot1'/tests\n\n" + " List all tests:\n" +
311 " --query tests\n\n" +
312 " List all tests and the bots running them:\n" +
313 " --query tests/bots\n\n" +
314 " List all tests that satisfy multiple parameters\n" +
315 " (separation of parameters by '&' symbol):\n" +
316 " --query tests/'device_os:Android&device_type:hammerhead'\n\n" +
317 " List all tests that run with a specific flag:\n" +
318 " --query bots/'--test-launcher-print-test-studio=always'\n\n" +
319 " List specific test (make sure you have quotes):\n"
320 " --query test/'test1'\n\n"
321 " List all bots running 'test1' " +
322 "(make sure you have quotes):\n" + " --query test/'test1'/bots"))
323 parser.add_argument(
324 '-n',
325 '--new-files',
326 action='store_true',
327 help=
328 'Write output files as .new.json. Useful during development so old and '
329 'new files can be looked at side-by-side.')
330 parser.add_argument('-v',
331 '--verbose',
332 action='store_true',
333 help='Increases verbosity. Affects consistency checks.')
334 parser.add_argument('waterfall_filters',
335 metavar='waterfalls',
336 type=str,
337 nargs='*',
338 help='Optional list of waterfalls to generate.')
339 parser.add_argument(
340 '--pyl-files-dir',
341 type=os.path.realpath,
342 help='Path to the directory containing the input .pyl files.')
343 parser.add_argument(
344 '--json',
345 metavar='JSON_FILE_PATH',
346 help='Outputs results into a json file. Only works with query function.'
347 )
Chong Guee622242020-10-28 18:17:35348 parser.add_argument('--isolate-map-file',
349 metavar='PATH',
350 help='path to additional isolate map files.',
351 default=[],
352 action='append',
353 dest='isolate_map_files')
Garrett Beaty1afaccc2020-06-25 19:58:15354 parser.add_argument(
355 '--infra-config-dir',
356 help='Path to the LUCI services configuration directory',
357 default=os.path.abspath(
358 os.path.join(os.path.dirname(__file__), '..', '..', 'infra',
359 'config')))
360 args = parser.parse_args(argv)
361 if args.json and not args.query:
362 parser.error(
363 "The --json flag can only be used with --query.") # pragma: no cover
364 args.infra_config_dir = os.path.abspath(args.infra_config_dir)
365 return args
366
Kenneth Russelleb60cbd22017-12-05 07:54:28367 def generate_abs_file_path(self, relative_path):
Garrett Beaty1afaccc2020-06-25 19:58:15368 return os.path.join(self.this_dir, relative_path)
Kenneth Russelleb60cbd22017-12-05 07:54:28369
Stephen Martinis7eb8b612018-09-21 00:17:50370 def print_line(self, line):
371 # Exists so that tests can mock
Jamie Madillcf4f8c72021-05-20 19:24:23372 print(line) # pragma: no cover
Stephen Martinis7eb8b612018-09-21 00:17:50373
Kenneth Russelleb60cbd22017-12-05 07:54:28374 def read_file(self, relative_path):
Garrett Beaty1afaccc2020-06-25 19:58:15375 with open(self.generate_abs_file_path(relative_path)) as fp:
376 return fp.read()
Kenneth Russelleb60cbd22017-12-05 07:54:28377
378 def write_file(self, relative_path, contents):
Garrett Beaty1afaccc2020-06-25 19:58:15379 with open(self.generate_abs_file_path(relative_path), 'wb') as fp:
Jamie Madillcf4f8c72021-05-20 19:24:23380 fp.write(contents.encode('utf-8'))
Kenneth Russelleb60cbd22017-12-05 07:54:28381
Zhiling Huangbe008172018-03-08 19:13:11382 def pyl_file_path(self, filename):
383 if self.args and self.args.pyl_files_dir:
384 return os.path.join(self.args.pyl_files_dir, filename)
385 return filename
386
Kenneth Russelleb60cbd22017-12-05 07:54:28387 def load_pyl_file(self, filename):
388 try:
Zhiling Huangbe008172018-03-08 19:13:11389 return ast.literal_eval(self.read_file(
390 self.pyl_file_path(filename)))
Kenneth Russelleb60cbd22017-12-05 07:54:28391 except (SyntaxError, ValueError) as e: # pragma: no cover
392 raise BBGenErr('Failed to parse pyl file "%s": %s' %
393 (filename, e)) # pragma: no cover
394
Kenneth Russell8a386d42018-06-02 09:48:01395 # TOOD(kbr): require that os_type be specified for all bots in waterfalls.pyl.
396 # Currently it is only mandatory for bots which run GPU tests. Change these to
397 # use [] instead of .get().
Kenneth Russelleb60cbd22017-12-05 07:54:28398 def is_android(self, tester_config):
399 return tester_config.get('os_type') == 'android'
400
Ben Pastenea9e583b2019-01-16 02:57:26401 def is_chromeos(self, tester_config):
402 return tester_config.get('os_type') == 'chromeos'
403
Brian Sheedy781c8ca42021-03-08 22:03:21404 def is_lacros(self, tester_config):
405 return tester_config.get('os_type') == 'lacros'
406
Kenneth Russell8a386d42018-06-02 09:48:01407 def is_linux(self, tester_config):
408 return tester_config.get('os_type') == 'linux'
409
Kai Ninomiya40de9f52019-10-18 21:38:49410 def is_mac(self, tester_config):
411 return tester_config.get('os_type') == 'mac'
412
413 def is_win(self, tester_config):
414 return tester_config.get('os_type') == 'win'
415
416 def is_win64(self, tester_config):
417 return (tester_config.get('os_type') == 'win' and
418 tester_config.get('browser_config') == 'release_x64')
419
Kenneth Russelleb60cbd22017-12-05 07:54:28420 def get_exception_for_test(self, test_name, test_config):
421 # gtests may have both "test" and "name" fields, and usually, if the "name"
422 # field is specified, it means that the same test is being repurposed
423 # multiple times with different command line arguments. To handle this case,
424 # prefer to lookup per the "name" field of the test itself, as opposed to
425 # the "test_name", which is actually the "test" field.
426 if 'name' in test_config:
427 return self.exceptions.get(test_config['name'])
428 else:
429 return self.exceptions.get(test_name)
430
Nico Weberb0b3f5862018-07-13 18:45:15431 def should_run_on_tester(self, waterfall, tester_name,test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28432 # Currently, the only reason a test should not run on a given tester is that
433 # it's in the exceptions. (Once the GPU waterfall generation script is
434 # incorporated here, the rules will become more complex.)
435 exception = self.get_exception_for_test(test_name, test_config)
436 if not exception:
437 return True
Kenneth Russell8ceeabf2017-12-11 17:53:28438 remove_from = None
Kenneth Russelleb60cbd22017-12-05 07:54:28439 remove_from = exception.get('remove_from')
Kenneth Russell8ceeabf2017-12-11 17:53:28440 if remove_from:
441 if tester_name in remove_from:
442 return False
443 # TODO(kbr): this code path was added for some tests (including
444 # android_webview_unittests) on one machine (Nougat Phone
445 # Tester) which exists with the same name on two waterfalls,
446 # chromium.android and chromium.fyi; the tests are run on one
447 # but not the other. Once the bots are all uniquely named (a
448 # different ongoing project) this code should be removed.
449 # TODO(kbr): add coverage.
450 return (tester_name + ' ' + waterfall['name']
451 not in remove_from) # pragma: no cover
452 return True
Kenneth Russelleb60cbd22017-12-05 07:54:28453
Nico Weber79dc5f6852018-07-13 19:38:49454 def get_test_modifications(self, test, test_name, tester_name):
Kenneth Russelleb60cbd22017-12-05 07:54:28455 exception = self.get_exception_for_test(test_name, test)
456 if not exception:
457 return None
Nico Weber79dc5f6852018-07-13 19:38:49458 return exception.get('modifications', {}).get(tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28459
Brian Sheedye6ea0ee2019-07-11 02:54:37460 def get_test_replacements(self, test, test_name, tester_name):
461 exception = self.get_exception_for_test(test_name, test)
462 if not exception:
463 return None
464 return exception.get('replacements', {}).get(tester_name)
465
Kenneth Russell8a386d42018-06-02 09:48:01466 def merge_command_line_args(self, arr, prefix, splitter):
467 prefix_len = len(prefix)
Kenneth Russell650995a2018-05-03 21:17:01468 idx = 0
469 first_idx = -1
Kenneth Russell8a386d42018-06-02 09:48:01470 accumulated_args = []
Kenneth Russell650995a2018-05-03 21:17:01471 while idx < len(arr):
472 flag = arr[idx]
473 delete_current_entry = False
Kenneth Russell8a386d42018-06-02 09:48:01474 if flag.startswith(prefix):
475 arg = flag[prefix_len:]
476 accumulated_args.extend(arg.split(splitter))
Kenneth Russell650995a2018-05-03 21:17:01477 if first_idx < 0:
478 first_idx = idx
479 else:
480 delete_current_entry = True
481 if delete_current_entry:
482 del arr[idx]
483 else:
484 idx += 1
485 if first_idx >= 0:
Kenneth Russell8a386d42018-06-02 09:48:01486 arr[first_idx] = prefix + splitter.join(accumulated_args)
487 return arr
488
489 def maybe_fixup_args_array(self, arr):
490 # The incoming array of strings may be an array of command line
491 # arguments. To make it easier to turn on certain features per-bot or
492 # per-test-suite, look specifically for certain flags and merge them
493 # appropriately.
494 # --enable-features=Feature1 --enable-features=Feature2
495 # are merged to:
496 # --enable-features=Feature1,Feature2
497 # and:
498 # --extra-browser-args=arg1 --extra-browser-args=arg2
499 # are merged to:
500 # --extra-browser-args=arg1 arg2
501 arr = self.merge_command_line_args(arr, '--enable-features=', ',')
502 arr = self.merge_command_line_args(arr, '--extra-browser-args=', ' ')
Yuly Novikov8c487e72020-10-16 20:00:29503 arr = self.merge_command_line_args(arr, '--test-launcher-filter-file=', ';')
Kenneth Russell650995a2018-05-03 21:17:01504 return arr
505
Brian Sheedya31578e2020-05-18 20:24:36506 def substitute_magic_args(self, test_config):
507 """Substitutes any magic substitution args present in |test_config|.
508
509 Substitutions are done in-place.
510
511 See buildbot_json_magic_substitutions.py for more information on this
512 feature.
513
514 Args:
515 test_config: A dict containing a configuration for a specific test on
516 a specific builder, e.g. the output of update_and_cleanup_test.
517 """
518 substituted_array = []
519 for arg in test_config.get('args', []):
520 if arg.startswith(magic_substitutions.MAGIC_SUBSTITUTION_PREFIX):
521 function = arg.replace(
522 magic_substitutions.MAGIC_SUBSTITUTION_PREFIX, '')
523 if hasattr(magic_substitutions, function):
524 substituted_array.extend(
525 getattr(magic_substitutions, function)(test_config))
526 else:
527 raise BBGenErr(
528 'Magic substitution function %s does not exist' % function)
529 else:
530 substituted_array.append(arg)
531 if substituted_array:
532 test_config['args'] = self.maybe_fixup_args_array(substituted_array)
533
Kenneth Russelleb60cbd22017-12-05 07:54:28534 def dictionary_merge(self, a, b, path=None, update=True):
535 """http://stackoverflow.com/questions/7204805/
536 python-dictionaries-of-dictionaries-merge
537 merges b into a
538 """
539 if path is None:
540 path = []
541 for key in b:
542 if key in a:
543 if isinstance(a[key], dict) and isinstance(b[key], dict):
544 self.dictionary_merge(a[key], b[key], path + [str(key)])
545 elif a[key] == b[key]:
546 pass # same leaf value
547 elif isinstance(a[key], list) and isinstance(b[key], list):
Stephen Martinis3bed2ab2018-04-23 19:42:06548 # Args arrays are lists of strings. Just concatenate them,
549 # and don't sort them, in order to keep some needed
550 # arguments adjacent (like --time-out-ms [arg], etc.)
Kenneth Russell8ceeabf2017-12-11 17:53:28551 if all(isinstance(x, str)
552 for x in itertools.chain(a[key], b[key])):
Kenneth Russell650995a2018-05-03 21:17:01553 a[key] = self.maybe_fixup_args_array(a[key] + b[key])
Kenneth Russell8ceeabf2017-12-11 17:53:28554 else:
555 # TODO(kbr): this only works properly if the two arrays are
556 # the same length, which is currently always the case in the
557 # swarming dimension_sets that we have to merge. It will fail
558 # to merge / override 'args' arrays which are different
559 # length.
Jamie Madillcf4f8c72021-05-20 19:24:23560 for idx in range(len(b[key])):
Kenneth Russell8ceeabf2017-12-11 17:53:28561 try:
562 a[key][idx] = self.dictionary_merge(a[key][idx], b[key][idx],
563 path + [str(key), str(idx)],
564 update=update)
Jeff Yoon8154e582019-12-03 23:30:01565 except (IndexError, TypeError):
566 raise BBGenErr('Error merging lists by key "%s" from source %s '
567 'into target %s at index %s. Verify target list '
568 'length is equal or greater than source'
569 % (str(key), str(b), str(a), str(idx)))
John Budorick5bc387fe2019-05-09 20:02:53570 elif update:
571 if b[key] is None:
572 del a[key]
573 else:
574 a[key] = b[key]
Kenneth Russelleb60cbd22017-12-05 07:54:28575 else:
576 raise BBGenErr('Conflict at %s' % '.'.join(
577 path + [str(key)])) # pragma: no cover
John Budorick5bc387fe2019-05-09 20:02:53578 elif b[key] is not None:
Kenneth Russelleb60cbd22017-12-05 07:54:28579 a[key] = b[key]
580 return a
581
John Budorickab108712018-09-01 00:12:21582 def initialize_args_for_test(
583 self, generated_test, tester_config, additional_arg_keys=None):
John Budorickab108712018-09-01 00:12:21584 args = []
585 args.extend(generated_test.get('args', []))
586 args.extend(tester_config.get('args', []))
John Budorickedfe7f872018-01-23 15:27:22587
Kenneth Russell8a386d42018-06-02 09:48:01588 def add_conditional_args(key, fn):
John Budorickab108712018-09-01 00:12:21589 val = generated_test.pop(key, [])
590 if fn(tester_config):
591 args.extend(val)
Kenneth Russell8a386d42018-06-02 09:48:01592
593 add_conditional_args('desktop_args', lambda cfg: not self.is_android(cfg))
Brian Sheedy781c8ca42021-03-08 22:03:21594 add_conditional_args('lacros_args', self.is_lacros)
Kenneth Russell8a386d42018-06-02 09:48:01595 add_conditional_args('linux_args', self.is_linux)
596 add_conditional_args('android_args', self.is_android)
Ben Pastene52890ace2019-05-24 20:03:36597 add_conditional_args('chromeos_args', self.is_chromeos)
Kai Ninomiya40de9f52019-10-18 21:38:49598 add_conditional_args('mac_args', self.is_mac)
599 add_conditional_args('win_args', self.is_win)
600 add_conditional_args('win64_args', self.is_win64)
Kenneth Russell8a386d42018-06-02 09:48:01601
John Budorickab108712018-09-01 00:12:21602 for key in additional_arg_keys or []:
603 args.extend(generated_test.pop(key, []))
604 args.extend(tester_config.get(key, []))
605
606 if args:
607 generated_test['args'] = self.maybe_fixup_args_array(args)
Kenneth Russell8a386d42018-06-02 09:48:01608
Kenneth Russelleb60cbd22017-12-05 07:54:28609 def initialize_swarming_dictionary_for_test(self, generated_test,
610 tester_config):
611 if 'swarming' not in generated_test:
612 generated_test['swarming'] = {}
Dirk Pranke81ff51c2017-12-09 19:24:28613 if not 'can_use_on_swarming_builders' in generated_test['swarming']:
614 generated_test['swarming'].update({
Jeff Yoon67c3e832020-02-08 07:39:38615 'can_use_on_swarming_builders': tester_config.get('use_swarming',
616 True)
Dirk Pranke81ff51c2017-12-09 19:24:28617 })
Kenneth Russelleb60cbd22017-12-05 07:54:28618 if 'swarming' in tester_config:
Ben Pastene796c62862018-06-13 02:40:03619 if ('dimension_sets' not in generated_test['swarming'] and
620 'dimension_sets' in tester_config['swarming']):
Kenneth Russelleb60cbd22017-12-05 07:54:28621 generated_test['swarming']['dimension_sets'] = copy.deepcopy(
622 tester_config['swarming']['dimension_sets'])
623 self.dictionary_merge(generated_test['swarming'],
624 tester_config['swarming'])
Brian Sheedybc984e242021-04-21 23:44:51625 # Apply any platform-specific Swarming dimensions after the generic ones.
Kenneth Russelleb60cbd22017-12-05 07:54:28626 if 'android_swarming' in generated_test:
627 if self.is_android(tester_config): # pragma: no cover
628 self.dictionary_merge(
629 generated_test['swarming'],
630 generated_test['android_swarming']) # pragma: no cover
631 del generated_test['android_swarming'] # pragma: no cover
Brian Sheedybc984e242021-04-21 23:44:51632 if 'chromeos_swarming' in generated_test:
633 if self.is_chromeos(tester_config): # pragma: no cover
634 self.dictionary_merge(
635 generated_test['swarming'],
636 generated_test['chromeos_swarming']) # pragma: no cover
637 del generated_test['chromeos_swarming'] # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:28638
639 def clean_swarming_dictionary(self, swarming_dict):
640 # Clean out redundant entries from a test's "swarming" dictionary.
641 # This is really only needed to retain 100% parity with the
642 # handwritten JSON files, and can be removed once all the files are
643 # autogenerated.
644 if 'shards' in swarming_dict:
645 if swarming_dict['shards'] == 1: # pragma: no cover
646 del swarming_dict['shards'] # pragma: no cover
Kenneth Russellfbda3c532017-12-08 23:57:24647 if 'hard_timeout' in swarming_dict:
648 if swarming_dict['hard_timeout'] == 0: # pragma: no cover
649 del swarming_dict['hard_timeout'] # pragma: no cover
Stephen Martinisf5f4ea22018-09-20 01:07:43650 if not swarming_dict.get('can_use_on_swarming_builders', False):
Kenneth Russelleb60cbd22017-12-05 07:54:28651 # Remove all other keys.
Jamie Madillcf4f8c72021-05-20 19:24:23652 for k in list(swarming_dict): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:28653 if k != 'can_use_on_swarming_builders': # pragma: no cover
654 del swarming_dict[k] # pragma: no cover
655
Stephen Martinis0382bc12018-09-17 22:29:07656 def update_and_cleanup_test(self, test, test_name, tester_name, tester_config,
657 waterfall):
658 # Apply swarming mixins.
Stephen Martinisb72f6d22018-10-04 23:29:01659 test = self.apply_all_mixins(
Stephen Martinis0382bc12018-09-17 22:29:07660 test, waterfall, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28661 # See if there are any exceptions that need to be merged into this
662 # test's specification.
Nico Weber79dc5f6852018-07-13 19:38:49663 modifications = self.get_test_modifications(test, test_name, tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28664 if modifications:
665 test = self.dictionary_merge(test, modifications)
Dirk Pranke1b767092017-12-07 04:44:23666 if 'swarming' in test:
667 self.clean_swarming_dictionary(test['swarming'])
Ben Pastenee012aea42019-05-14 22:32:28668 # Ensure all Android Swarming tests run only on userdebug builds if another
669 # build type was not specified.
670 if 'swarming' in test and self.is_android(tester_config):
671 for d in test['swarming'].get('dimension_sets', []):
Ben Pastened15aa8a2019-05-16 16:59:22672 if d.get('os') == 'Android' and not d.get('device_os_type'):
Ben Pastenee012aea42019-05-14 22:32:28673 d['device_os_type'] = 'userdebug'
Brian Sheedye6ea0ee2019-07-11 02:54:37674 self.replace_test_args(test, test_name, tester_name)
Ben Pastenee012aea42019-05-14 22:32:28675
Kenneth Russelleb60cbd22017-12-05 07:54:28676 return test
677
Brian Sheedye6ea0ee2019-07-11 02:54:37678 def replace_test_args(self, test, test_name, tester_name):
679 replacements = self.get_test_replacements(
680 test, test_name, tester_name) or {}
681 valid_replacement_keys = ['args', 'non_precommit_args', 'precommit_args']
Jamie Madillcf4f8c72021-05-20 19:24:23682 for key, replacement_dict in replacements.items():
Brian Sheedye6ea0ee2019-07-11 02:54:37683 if key not in valid_replacement_keys:
684 raise BBGenErr(
685 'Given replacement key %s for %s on %s is not in the list of valid '
686 'keys %s' % (key, test_name, tester_name, valid_replacement_keys))
Jamie Madillcf4f8c72021-05-20 19:24:23687 for replacement_key, replacement_val in replacement_dict.items():
Brian Sheedye6ea0ee2019-07-11 02:54:37688 found_key = False
689 for i, test_key in enumerate(test.get(key, [])):
690 # Handle both the key/value being replaced being defined as two
691 # separate items or as key=value.
692 if test_key == replacement_key:
693 found_key = True
694 # Handle flags without values.
695 if replacement_val == None:
696 del test[key][i]
697 else:
698 test[key][i+1] = replacement_val
699 break
700 elif test_key.startswith(replacement_key + '='):
701 found_key = True
702 if replacement_val == None:
703 del test[key][i]
704 else:
705 test[key][i] = '%s=%s' % (replacement_key, replacement_val)
706 break
707 if not found_key:
708 raise BBGenErr('Could not find %s in existing list of values for key '
709 '%s in %s on %s' % (replacement_key, key, test_name,
710 tester_name))
711
Shenghua Zhangaba8bad2018-02-07 02:12:09712 def add_common_test_properties(self, test, tester_config):
Brian Sheedy5ea8f6c62020-05-21 03:05:05713 if self.is_chromeos(tester_config) and tester_config.get('use_swarming',
Ben Pastenea9e583b2019-01-16 02:57:26714 True):
715 # The presence of the "device_type" dimension indicates that the tests
Brian Sheedy9493da892020-05-13 22:58:06716 # are targeting CrOS hardware and so need the special trigger script.
717 dimension_sets = test['swarming']['dimension_sets']
Ben Pastenea9e583b2019-01-16 02:57:26718 if all('device_type' in ds for ds in dimension_sets):
719 test['trigger_script'] = {
720 'script': '//testing/trigger_scripts/chromeos_device_trigger.py',
721 }
Shenghua Zhangaba8bad2018-02-07 02:12:09722
Yuly Novikov26dd47052021-02-11 00:57:14723 def add_logdog_butler_cipd_package(self, tester_config, result):
724 if not tester_config.get('skip_cipd_packages', False):
725 cipd_packages = result['swarming'].get('cipd_packages', [])
726 already_added = len([
727 package for package in cipd_packages
728 if package.get('cipd_package', "").find('logdog/butler') > 0
729 ]) > 0
730 if not already_added:
731 cipd_packages.append({
732 'cipd_package':
733 'infra/tools/luci/logdog/butler/${platform}',
734 'location':
735 'bin',
736 'revision':
737 'git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c',
738 })
739 result['swarming']['cipd_packages'] = cipd_packages
740
Ben Pastene858f4be2019-01-09 23:52:09741 def add_android_presentation_args(self, tester_config, test_name, result):
742 args = result.get('args', [])
John Budorick262ae112019-07-12 19:24:38743 bucket = tester_config.get('results_bucket', 'chromium-result-details')
744 args.append('--gs-results-bucket=%s' % bucket)
Ben Pastene858f4be2019-01-09 23:52:09745 if (result['swarming']['can_use_on_swarming_builders'] and not
746 tester_config.get('skip_merge_script', False)):
747 result['merge'] = {
748 'args': [
749 '--bucket',
John Budorick262ae112019-07-12 19:24:38750 bucket,
Ben Pastene858f4be2019-01-09 23:52:09751 '--test-name',
Rakib M. Hasanc9e01c62020-07-27 22:48:12752 result.get('name', test_name)
Ben Pastene858f4be2019-01-09 23:52:09753 ],
754 'script': '//build/android/pylib/results/presentation/'
755 'test_results_presentation.py',
756 }
Ben Pastene858f4be2019-01-09 23:52:09757 if not tester_config.get('skip_output_links', False):
758 result['swarming']['output_links'] = [
759 {
760 'link': [
761 'https://luci-logdog.appspot.com/v/?s',
762 '=android%2Fswarming%2Flogcats%2F',
763 '${TASK_ID}%2F%2B%2Funified_logcats',
764 ],
765 'name': 'shard #${SHARD_INDEX} logcats',
766 },
767 ]
768 if args:
769 result['args'] = args
770
Kenneth Russelleb60cbd22017-12-05 07:54:28771 def generate_gtest(self, waterfall, tester_name, tester_config, test_name,
772 test_config):
773 if not self.should_run_on_tester(
Nico Weberb0b3f5862018-07-13 18:45:15774 waterfall, tester_name, test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28775 return None
776 result = copy.deepcopy(test_config)
777 if 'test' in result:
Rakib M. Hasanc9e01c62020-07-27 22:48:12778 if 'name' not in result:
779 result['name'] = test_name
Kenneth Russelleb60cbd22017-12-05 07:54:28780 else:
781 result['test'] = test_name
782 self.initialize_swarming_dictionary_for_test(result, tester_config)
John Budorickab108712018-09-01 00:12:21783
784 self.initialize_args_for_test(
785 result, tester_config, additional_arg_keys=['gtest_args'])
Jamie Madilla8be0d72020-10-02 05:24:04786 if self.is_android(tester_config) and tester_config.get(
Yuly Novikov26dd47052021-02-11 00:57:14787 'use_swarming', True):
788 if not test_config.get('use_isolated_scripts_api', False):
789 # TODO(https://crbug.com/1137998) make Android presentation work with
790 # isolated scripts in test_results_presentation.py merge script
791 self.add_android_presentation_args(tester_config, test_name, result)
792 result['args'] = result.get('args', []) + ['--recover-devices']
793 self.add_logdog_butler_cipd_package(tester_config, result)
Benjamin Pastene766d48f52017-12-18 21:47:42794
Stephen Martinis0382bc12018-09-17 22:29:07795 result = self.update_and_cleanup_test(
796 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09797 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36798 self.substitute_magic_args(result)
Stephen Martinisbc7b7772019-05-01 22:01:43799
800 if not result.get('merge'):
801 # TODO(https://crbug.com/958376): Consider adding the ability to not have
802 # this default.
Jamie Madilla8be0d72020-10-02 05:24:04803 if test_config.get('use_isolated_scripts_api', False):
804 merge_script = 'standard_isolated_script_merge'
805 else:
806 merge_script = 'standard_gtest_merge'
807
Stephen Martinisbc7b7772019-05-01 22:01:43808 result['merge'] = {
Jamie Madilla8be0d72020-10-02 05:24:04809 'script': '//testing/merge_scripts/%s.py' % merge_script,
810 'args': [],
Stephen Martinisbc7b7772019-05-01 22:01:43811 }
Kenneth Russelleb60cbd22017-12-05 07:54:28812 return result
813
814 def generate_isolated_script_test(self, waterfall, tester_name, tester_config,
815 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01816 if not self.should_run_on_tester(waterfall, tester_name, test_name,
817 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28818 return None
819 result = copy.deepcopy(test_config)
820 result['isolate_name'] = result.get('isolate_name', test_name)
Jeff Yoonb8bfdbf32020-03-13 19:14:43821 result['name'] = result.get('name', test_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28822 self.initialize_swarming_dictionary_for_test(result, tester_config)
Kenneth Russell8a386d42018-06-02 09:48:01823 self.initialize_args_for_test(result, tester_config)
Yuly Novikov26dd47052021-02-11 00:57:14824 if self.is_android(tester_config) and tester_config.get(
825 'use_swarming', True):
826 if tester_config.get('use_android_presentation', False):
827 # TODO(https://crbug.com/1137998) make Android presentation work with
828 # isolated scripts in test_results_presentation.py merge script
829 self.add_android_presentation_args(tester_config, test_name, result)
830 self.add_logdog_butler_cipd_package(tester_config, result)
Stephen Martinis0382bc12018-09-17 22:29:07831 result = self.update_and_cleanup_test(
832 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09833 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36834 self.substitute_magic_args(result)
Stephen Martinisf50047062019-05-06 22:26:17835
836 if not result.get('merge'):
837 # TODO(https://crbug.com/958376): Consider adding the ability to not have
838 # this default.
839 result['merge'] = {
840 'script': '//testing/merge_scripts/standard_isolated_script_merge.py',
841 'args': [],
842 }
Kenneth Russelleb60cbd22017-12-05 07:54:28843 return result
844
845 def generate_script_test(self, waterfall, tester_name, tester_config,
846 test_name, test_config):
Brian Sheedy158cd0f2019-04-26 01:12:44847 # TODO(https://crbug.com/953072): Remove this check whenever a better
848 # long-term solution is implemented.
849 if (waterfall.get('forbid_script_tests', False) or
850 waterfall['machines'][tester_name].get('forbid_script_tests', False)):
851 raise BBGenErr('Attempted to generate a script test on tester ' +
852 tester_name + ', which explicitly forbids script tests')
Kenneth Russell8a386d42018-06-02 09:48:01853 if not self.should_run_on_tester(waterfall, tester_name, test_name,
854 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28855 return None
856 result = {
857 'name': test_name,
858 'script': test_config['script']
859 }
Stephen Martinis0382bc12018-09-17 22:29:07860 result = self.update_and_cleanup_test(
861 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36862 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28863 return result
864
865 def generate_junit_test(self, waterfall, tester_name, tester_config,
866 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01867 if not self.should_run_on_tester(waterfall, tester_name, test_name,
868 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28869 return None
John Budorickdef6acb2019-09-17 22:51:09870 result = copy.deepcopy(test_config)
871 result.update({
John Budorickcadc4952019-09-16 23:51:37872 'name': test_name,
873 'test': test_config.get('test', test_name),
John Budorickdef6acb2019-09-17 22:51:09874 })
875 self.initialize_args_for_test(result, tester_config)
876 result = self.update_and_cleanup_test(
877 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36878 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28879 return result
880
Xinan Lin05fb9c1752020-12-17 00:15:52881 def generate_skylab_test(self, waterfall, tester_name, tester_config,
882 test_name, test_config):
883 if not self.should_run_on_tester(waterfall, tester_name, test_name,
884 test_config):
885 return None
886 result = copy.deepcopy(test_config)
887 result.update({
888 'test': test_name,
889 })
890 self.initialize_args_for_test(result, tester_config)
891 result = self.update_and_cleanup_test(result, test_name, tester_name,
892 tester_config, waterfall)
893 self.substitute_magic_args(result)
894 return result
895
Stephen Martinis2a0667022018-09-25 22:31:14896 def substitute_gpu_args(self, tester_config, swarming_config, args):
Kenneth Russell8a386d42018-06-02 09:48:01897 substitutions = {
898 # Any machine in waterfalls.pyl which desires to run GPU tests
899 # must provide the os_type key.
900 'os_type': tester_config['os_type'],
901 'gpu_vendor_id': '0',
902 'gpu_device_id': '0',
903 }
Stephen Martinis2a0667022018-09-25 22:31:14904 dimension_set = swarming_config['dimension_sets'][0]
Kenneth Russell8a386d42018-06-02 09:48:01905 if 'gpu' in dimension_set:
906 # First remove the driver version, then split into vendor and device.
907 gpu = dimension_set['gpu']
Yuly Novikove4b2fef2020-09-04 05:53:11908 if gpu != 'none':
909 gpu = gpu.split('-')[0].split(':')
910 substitutions['gpu_vendor_id'] = gpu[0]
911 substitutions['gpu_device_id'] = gpu[1]
Kenneth Russell8a386d42018-06-02 09:48:01912 return [string.Template(arg).safe_substitute(substitutions) for arg in args]
913
914 def generate_gpu_telemetry_test(self, waterfall, tester_name, tester_config,
Bo Liu555a0f92019-03-29 12:11:56915 test_name, test_config, is_android_webview):
Kenneth Russell8a386d42018-06-02 09:48:01916 # These are all just specializations of isolated script tests with
917 # a bunch of boilerplate command line arguments added.
918
919 # The step name must end in 'test' or 'tests' in order for the
920 # results to automatically show up on the flakiness dashboard.
921 # (At least, this was true some time ago.) Continue to use this
922 # naming convention for the time being to minimize changes.
923 step_name = test_config.get('name', test_name)
924 if not (step_name.endswith('test') or step_name.endswith('tests')):
925 step_name = '%s_tests' % step_name
926 result = self.generate_isolated_script_test(
927 waterfall, tester_name, tester_config, step_name, test_config)
928 if not result:
929 return None
Chong Gub75754b32020-03-13 16:39:20930 result['isolate_name'] = test_config.get(
Brian Sheedyf74819b2021-06-04 01:38:38931 'isolate_name',
932 self.get_default_isolate_name(tester_config, is_android_webview))
Chan Liab7d8dd82020-04-24 23:42:19933
Chan Lia3ad1502020-04-28 05:32:11934 # Populate test_id_prefix.
Brian Sheedyf74819b2021-06-04 01:38:38935 gn_entry = self.gn_isolate_map[result['isolate_name']]
Chan Li17d969f92020-07-10 00:50:03936 result['test_id_prefix'] = 'ninja:%s/' % gn_entry['label']
Chan Liab7d8dd82020-04-24 23:42:19937
Kenneth Russell8a386d42018-06-02 09:48:01938 args = result.get('args', [])
939 test_to_run = result.pop('telemetry_test_name', test_name)
erikchen6da2d9b2018-08-03 23:01:14940
941 # These tests upload and download results from cloud storage and therefore
942 # aren't idempotent yet. https://crbug.com/549140.
943 result['swarming']['idempotent'] = False
944
Kenneth Russell44910c32018-12-03 23:35:11945 # The GPU tests act much like integration tests for the entire browser, and
946 # tend to uncover flakiness bugs more readily than other test suites. In
947 # order to surface any flakiness more readily to the developer of the CL
948 # which is introducing it, we disable retries with patch on the commit
949 # queue.
950 result['should_retry_with_patch'] = False
951
Bo Liu555a0f92019-03-29 12:11:56952 browser = ('android-webview-instrumentation'
953 if is_android_webview else tester_config['browser_config'])
Brian Sheedy4053a702020-07-28 02:09:52954
955 # Most platforms require --enable-logging=stderr to get useful browser logs.
956 # However, this actively messes with logging on CrOS (because Chrome's
957 # stderr goes nowhere on CrOS) AND --log-level=0 is required for some reason
958 # in order to see JavaScript console messages. See
959 # https://chromium.googlesource.com/chromium/src.git/+/HEAD/docs/chrome_os_logging.md
960 logging_arg = '--log-level=0' if self.is_chromeos(
961 tester_config) else '--enable-logging=stderr'
962
Kenneth Russell8a386d42018-06-02 09:48:01963 args = [
Bo Liu555a0f92019-03-29 12:11:56964 test_to_run,
965 '--show-stdout',
966 '--browser=%s' % browser,
967 # --passthrough displays more of the logging in Telemetry when
968 # run via typ, in particular some of the warnings about tests
969 # being expected to fail, but passing.
970 '--passthrough',
971 '-v',
Brian Sheedy4053a702020-07-28 02:09:52972 '--extra-browser-args=%s --js-flags=--expose-gc' % logging_arg,
Kenneth Russell8a386d42018-06-02 09:48:01973 ] + args
974 result['args'] = self.maybe_fixup_args_array(self.substitute_gpu_args(
Stephen Martinis2a0667022018-09-25 22:31:14975 tester_config, result['swarming'], args))
Kenneth Russell8a386d42018-06-02 09:48:01976 return result
977
Brian Sheedyf74819b2021-06-04 01:38:38978 def get_default_isolate_name(self, tester_config, is_android_webview):
979 if self.is_android(tester_config):
980 if is_android_webview:
981 return 'telemetry_gpu_integration_test_android_webview'
982 return (
983 'telemetry_gpu_integration_test' +
984 BROWSER_CONFIG_TO_TARGET_SUFFIX_MAP[tester_config['browser_config']])
985 else:
986 return 'telemetry_gpu_integration_test'
987
Kenneth Russelleb60cbd22017-12-05 07:54:28988 def get_test_generator_map(self):
989 return {
Bo Liu555a0f92019-03-29 12:11:56990 'android_webview_gpu_telemetry_tests':
991 GPUTelemetryTestGenerator(self, is_android_webview=True),
Bo Liu555a0f92019-03-29 12:11:56992 'gpu_telemetry_tests':
993 GPUTelemetryTestGenerator(self),
994 'gtest_tests':
995 GTestGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56996 'isolated_scripts':
997 IsolatedScriptTestGenerator(self),
998 'junit_tests':
999 JUnitGenerator(self),
1000 'scripts':
1001 ScriptGenerator(self),
Xinan Lin05fb9c1752020-12-17 00:15:521002 'skylab_tests':
1003 SkylabGenerator(self),
Kenneth Russelleb60cbd22017-12-05 07:54:281004 }
1005
Kenneth Russell8a386d42018-06-02 09:48:011006 def get_test_type_remapper(self):
1007 return {
1008 # These are a specialization of isolated_scripts with a bunch of
1009 # boilerplate command line arguments added to each one.
Bo Liu555a0f92019-03-29 12:11:561010 'android_webview_gpu_telemetry_tests': 'isolated_scripts',
Kenneth Russell8a386d42018-06-02 09:48:011011 'gpu_telemetry_tests': 'isolated_scripts',
1012 }
1013
Jeff Yoon67c3e832020-02-08 07:39:381014 def check_composition_type_test_suites(self, test_type,
1015 additional_validators=None):
1016 """Pre-pass to catch errors reliabily for compound/matrix suites"""
1017 validators = [check_compound_references,
1018 check_basic_references,
1019 check_conflicting_definitions]
1020 if additional_validators:
1021 validators += additional_validators
1022
1023 target_suites = self.test_suites.get(test_type, {})
1024 other_test_type = ('compound_suites'
1025 if test_type == 'matrix_compound_suites'
1026 else 'matrix_compound_suites')
1027 other_suites = self.test_suites.get(other_test_type, {})
Jeff Yoon8154e582019-12-03 23:30:011028 basic_suites = self.test_suites.get('basic_suites', {})
1029
Jamie Madillcf4f8c72021-05-20 19:24:231030 for suite, suite_def in target_suites.items():
Jeff Yoon8154e582019-12-03 23:30:011031 if suite in basic_suites:
1032 raise BBGenErr('%s names may not duplicate basic test suite names '
1033 '(error found while processsing %s)'
1034 % (test_type, suite))
Nodir Turakulov28232afd2019-12-17 18:02:011035
Jeff Yoon67c3e832020-02-08 07:39:381036 seen_tests = {}
1037 for sub_suite in suite_def:
1038 for validator in validators:
1039 validator(
1040 basic_suites=basic_suites,
1041 other_test_suites=other_suites,
1042 seen_tests=seen_tests,
1043 sub_suite=sub_suite,
1044 suite=suite,
1045 suite_def=suite_def,
1046 target_test_suites=target_suites,
1047 test_type=test_type,
Jeff Yoonda581c32020-03-06 03:56:051048 all_variants=self.variants
Jeff Yoon67c3e832020-02-08 07:39:381049 )
Kenneth Russelleb60cbd22017-12-05 07:54:281050
Stephen Martinis54d64ad2018-09-21 22:16:201051 def flatten_test_suites(self):
1052 new_test_suites = {}
Jeff Yoon8154e582019-12-03 23:30:011053 test_types = ['basic_suites', 'compound_suites', 'matrix_compound_suites']
1054 for category in test_types:
Jamie Madillcf4f8c72021-05-20 19:24:231055 for name, value in self.test_suites.get(category, {}).items():
Jeff Yoon8154e582019-12-03 23:30:011056 new_test_suites[name] = value
Stephen Martinis54d64ad2018-09-21 22:16:201057 self.test_suites = new_test_suites
1058
Chan Lia3ad1502020-04-28 05:32:111059 def resolve_test_id_prefixes(self):
Jamie Madillcf4f8c72021-05-20 19:24:231060 for suite in self.test_suites['basic_suites'].values():
1061 for key, test in suite.items():
Dirk Pranke0e879b22020-07-16 23:53:561062 assert isinstance(test, dict)
Nodir Turakulovfce34292019-12-18 17:05:411063
1064 # This assumes the recipe logic which prefers 'test' to 'isolate_name'
John Palmera8515fca2021-05-20 03:35:321065 # https://source.chromium.org/chromium/chromium/tools/build/+/main:scripts/slave/recipe_modules/chromium_tests/generators.py;l=89;drc=14c062ba0eb418d3c4623dde41a753241b9df06b
Nodir Turakulovfce34292019-12-18 17:05:411066 # TODO(crbug.com/1035124): clean this up.
1067 isolate_name = test.get('test') or test.get('isolate_name') or key
1068 gn_entry = self.gn_isolate_map.get(isolate_name)
1069 if gn_entry:
Corentin Wallez55b8e772020-04-24 17:39:281070 label = gn_entry['label']
1071
1072 if label.count(':') != 1:
1073 raise BBGenErr(
1074 'Malformed GN label "%s" in gn_isolate_map for key "%s",'
1075 ' implicit names (like //f/b meaning //f/b:b) are disallowed.' %
1076 (label, isolate_name))
1077 if label.split(':')[1] != isolate_name:
1078 raise BBGenErr(
1079 'gn_isolate_map key name "%s" doesn\'t match GN target name in'
1080 ' label "%s" see http://crbug.com/1071091 for details.' %
1081 (isolate_name, label))
1082
Chan Lia3ad1502020-04-28 05:32:111083 test['test_id_prefix'] = 'ninja:%s/' % label
Nodir Turakulovfce34292019-12-18 17:05:411084 else: # pragma: no cover
1085 # Some tests do not have an entry gn_isolate_map.pyl, such as
1086 # telemetry tests.
1087 # TODO(crbug.com/1035304): require an entry in gn_isolate_map.
1088 pass
1089
Kenneth Russelleb60cbd22017-12-05 07:54:281090 def resolve_composition_test_suites(self):
Jeff Yoon8154e582019-12-03 23:30:011091 self.check_composition_type_test_suites('compound_suites')
Stephen Martinis54d64ad2018-09-21 22:16:201092
Jeff Yoon8154e582019-12-03 23:30:011093 compound_suites = self.test_suites.get('compound_suites', {})
1094 # check_composition_type_test_suites() checks that all basic suites
1095 # referenced by compound suites exist.
1096 basic_suites = self.test_suites.get('basic_suites')
1097
Jamie Madillcf4f8c72021-05-20 19:24:231098 for name, value in compound_suites.items():
Jeff Yoon8154e582019-12-03 23:30:011099 # Resolve this to a dictionary.
1100 full_suite = {}
1101 for entry in value:
1102 suite = basic_suites[entry]
1103 full_suite.update(suite)
1104 compound_suites[name] = full_suite
1105
Jeff Yoon85fb8df2020-08-20 16:47:431106 def resolve_variants(self, basic_test_definition, variants, mixins):
Jeff Yoon67c3e832020-02-08 07:39:381107 """ Merge variant-defined configurations to each test case definition in a
1108 test suite.
1109
1110 The output maps a unique test name to an array of configurations because
1111 there may exist more than one definition for a test name using variants. The
1112 test name is referenced while mapping machines to test suites, so unpacking
1113 the array is done by the generators.
1114
1115 Args:
1116 basic_test_definition: a {} defined test suite in the format
1117 test_name:test_config
1118 variants: an [] of {} defining configurations to be applied to each test
1119 case in the basic test_definition
1120
1121 Return:
1122 a {} of test_name:[{}], where each {} is a merged configuration
1123 """
1124
1125 # Each test in a basic test suite will have a definition per variant.
1126 test_suite = {}
Jamie Madillcf4f8c72021-05-20 19:24:231127 for test_name, test_config in basic_test_definition.items():
Jeff Yoon67c3e832020-02-08 07:39:381128 definitions = []
1129 for variant in variants:
Jeff Yoonda581c32020-03-06 03:56:051130 # Unpack the variant from variants.pyl if it's string based.
1131 if isinstance(variant, str):
1132 variant = self.variants[variant]
1133
Jeff Yoon67c3e832020-02-08 07:39:381134 # Clone a copy of test_config so that we can have a uniquely updated
1135 # version of it per variant
1136 cloned_config = copy.deepcopy(test_config)
1137 # The variant definition needs to be re-used for each test, so we'll
1138 # create a clone and work with it as well.
1139 cloned_variant = copy.deepcopy(variant)
1140
1141 cloned_config['args'] = (cloned_config.get('args', []) +
1142 cloned_variant.get('args', []))
1143 cloned_config['mixins'] = (cloned_config.get('mixins', []) +
Jeff Yoon85fb8df2020-08-20 16:47:431144 cloned_variant.get('mixins', []) + mixins)
Jeff Yoon67c3e832020-02-08 07:39:381145
1146 basic_swarming_def = cloned_config.get('swarming', {})
1147 variant_swarming_def = cloned_variant.get('swarming', {})
1148 if basic_swarming_def and variant_swarming_def:
1149 if ('dimension_sets' in basic_swarming_def and
1150 'dimension_sets' in variant_swarming_def):
1151 # Retain swarming dimension set merge behavior when both variant and
1152 # the basic test configuration both define it
1153 self.dictionary_merge(basic_swarming_def, variant_swarming_def)
1154 # Remove dimension_sets from the variant definition, so that it does
1155 # not replace what's been done by dictionary_merge in the update
1156 # call below.
1157 del variant_swarming_def['dimension_sets']
1158
1159 # Update the swarming definition with whatever is defined for swarming
1160 # by the variant.
1161 basic_swarming_def.update(variant_swarming_def)
1162 cloned_config['swarming'] = basic_swarming_def
1163
Xinan Lin05fb9c1752020-12-17 00:15:521164 # Copy all skylab fields defined by the variant.
1165 skylab_config = cloned_variant.get('skylab')
1166 if skylab_config:
1167 for k, v in skylab_config.items():
1168 cloned_config[k] = v
1169
Jeff Yoon67c3e832020-02-08 07:39:381170 # The identifier is used to make the name of the test unique.
1171 # Generators in the recipe uniquely identify a test by it's name, so we
1172 # don't want to have the same name for each variant.
1173 cloned_config['name'] = '{}_{}'.format(test_name,
1174 cloned_variant['identifier'])
Jeff Yoon67c3e832020-02-08 07:39:381175 definitions.append(cloned_config)
1176 test_suite[test_name] = definitions
1177 return test_suite
1178
Jeff Yoon8154e582019-12-03 23:30:011179 def resolve_matrix_compound_test_suites(self):
Jeff Yoon67c3e832020-02-08 07:39:381180 self.check_composition_type_test_suites('matrix_compound_suites',
1181 [check_matrix_identifier])
Jeff Yoon8154e582019-12-03 23:30:011182
1183 matrix_compound_suites = self.test_suites.get('matrix_compound_suites', {})
Jeff Yoon67c3e832020-02-08 07:39:381184 # check_composition_type_test_suites() checks that all basic suites are
Jeff Yoon8154e582019-12-03 23:30:011185 # referenced by matrix suites exist.
1186 basic_suites = self.test_suites.get('basic_suites')
1187
Jamie Madillcf4f8c72021-05-20 19:24:231188 for test_name, matrix_config in matrix_compound_suites.items():
Jeff Yoon8154e582019-12-03 23:30:011189 full_suite = {}
Jeff Yoon67c3e832020-02-08 07:39:381190
Jamie Madillcf4f8c72021-05-20 19:24:231191 for test_suite, mtx_test_suite_config in matrix_config.items():
Jeff Yoon67c3e832020-02-08 07:39:381192 basic_test_def = copy.deepcopy(basic_suites[test_suite])
1193
1194 if 'variants' in mtx_test_suite_config:
Jeff Yoon85fb8df2020-08-20 16:47:431195 mixins = mtx_test_suite_config.get('mixins', [])
Jeff Yoon67c3e832020-02-08 07:39:381196 result = self.resolve_variants(basic_test_def,
Jeff Yoon85fb8df2020-08-20 16:47:431197 mtx_test_suite_config['variants'],
1198 mixins)
Jeff Yoon67c3e832020-02-08 07:39:381199 full_suite.update(result)
1200 matrix_compound_suites[test_name] = full_suite
Kenneth Russelleb60cbd22017-12-05 07:54:281201
1202 def link_waterfalls_to_test_suites(self):
1203 for waterfall in self.waterfalls:
Jamie Madillcf4f8c72021-05-20 19:24:231204 for tester_name, tester in waterfall['machines'].items():
1205 for suite, value in tester.get('test_suites', {}).items():
Kenneth Russelleb60cbd22017-12-05 07:54:281206 if not value in self.test_suites:
1207 # Hard / impossible to cover this in the unit test.
1208 raise self.unknown_test_suite(
1209 value, tester_name, waterfall['name']) # pragma: no cover
1210 tester['test_suites'][suite] = self.test_suites[value]
1211
1212 def load_configuration_files(self):
1213 self.waterfalls = self.load_pyl_file('waterfalls.pyl')
1214 self.test_suites = self.load_pyl_file('test_suites.pyl')
1215 self.exceptions = self.load_pyl_file('test_suite_exceptions.pyl')
Stephen Martinisb72f6d22018-10-04 23:29:011216 self.mixins = self.load_pyl_file('mixins.pyl')
Nodir Turakulovfce34292019-12-18 17:05:411217 self.gn_isolate_map = self.load_pyl_file('gn_isolate_map.pyl')
Chong Guee622242020-10-28 18:17:351218 for isolate_map in self.args.isolate_map_files:
1219 isolate_map = self.load_pyl_file(isolate_map)
1220 duplicates = set(isolate_map).intersection(self.gn_isolate_map)
1221 if duplicates:
1222 raise BBGenErr('Duplicate targets in isolate map files: %s.' %
1223 ', '.join(duplicates))
1224 self.gn_isolate_map.update(isolate_map)
1225
Jeff Yoonda581c32020-03-06 03:56:051226 self.variants = self.load_pyl_file('variants.pyl')
Kenneth Russelleb60cbd22017-12-05 07:54:281227
1228 def resolve_configuration_files(self):
Chan Lia3ad1502020-04-28 05:32:111229 self.resolve_test_id_prefixes()
Kenneth Russelleb60cbd22017-12-05 07:54:281230 self.resolve_composition_test_suites()
Jeff Yoon8154e582019-12-03 23:30:011231 self.resolve_matrix_compound_test_suites()
1232 self.flatten_test_suites()
Kenneth Russelleb60cbd22017-12-05 07:54:281233 self.link_waterfalls_to_test_suites()
1234
Nico Weberd18b8962018-05-16 19:39:381235 def unknown_bot(self, bot_name, waterfall_name):
1236 return BBGenErr(
1237 'Unknown bot name "%s" on waterfall "%s"' % (bot_name, waterfall_name))
1238
Kenneth Russelleb60cbd22017-12-05 07:54:281239 def unknown_test_suite(self, suite_name, bot_name, waterfall_name):
1240 return BBGenErr(
Nico Weberd18b8962018-05-16 19:39:381241 'Test suite %s from machine %s on waterfall %s not present in '
Kenneth Russelleb60cbd22017-12-05 07:54:281242 'test_suites.pyl' % (suite_name, bot_name, waterfall_name))
1243
1244 def unknown_test_suite_type(self, suite_type, bot_name, waterfall_name):
1245 return BBGenErr(
1246 'Unknown test suite type ' + suite_type + ' in bot ' + bot_name +
1247 ' on waterfall ' + waterfall_name)
1248
Stephen Martinisb72f6d22018-10-04 23:29:011249 def apply_all_mixins(self, test, waterfall, builder_name, builder):
Stephen Martinis0382bc12018-09-17 22:29:071250 """Applies all present swarming mixins to the test for a given builder.
Stephen Martinisb6a50492018-09-12 23:59:321251
1252 Checks in the waterfall, builder, and test objects for mixins.
1253 """
1254 def valid_mixin(mixin_name):
1255 """Asserts that the mixin is valid."""
Stephen Martinisb72f6d22018-10-04 23:29:011256 if mixin_name not in self.mixins:
Stephen Martinisb6a50492018-09-12 23:59:321257 raise BBGenErr("bad mixin %s" % mixin_name)
Jeff Yoon67c3e832020-02-08 07:39:381258
Stephen Martinisb6a50492018-09-12 23:59:321259 def must_be_list(mixins, typ, name):
1260 """Asserts that given mixins are a list."""
1261 if not isinstance(mixins, list):
1262 raise BBGenErr("'%s' in %s '%s' must be a list" % (mixins, typ, name))
1263
Brian Sheedy7658c982020-01-08 02:27:581264 test_name = test.get('name')
1265 remove_mixins = set()
1266 if 'remove_mixins' in builder:
1267 must_be_list(builder['remove_mixins'], 'builder', builder_name)
1268 for rm in builder['remove_mixins']:
1269 valid_mixin(rm)
1270 remove_mixins.add(rm)
1271 if 'remove_mixins' in test:
1272 must_be_list(test['remove_mixins'], 'test', test_name)
1273 for rm in test['remove_mixins']:
1274 valid_mixin(rm)
1275 remove_mixins.add(rm)
1276 del test['remove_mixins']
1277
Stephen Martinisb72f6d22018-10-04 23:29:011278 if 'mixins' in waterfall:
1279 must_be_list(waterfall['mixins'], 'waterfall', waterfall['name'])
1280 for mixin in waterfall['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581281 if mixin in remove_mixins:
1282 continue
Stephen Martinisb6a50492018-09-12 23:59:321283 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011284 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321285
Stephen Martinisb72f6d22018-10-04 23:29:011286 if 'mixins' in builder:
1287 must_be_list(builder['mixins'], 'builder', builder_name)
1288 for mixin in builder['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581289 if mixin in remove_mixins:
1290 continue
Stephen Martinisb6a50492018-09-12 23:59:321291 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011292 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321293
Stephen Martinisb72f6d22018-10-04 23:29:011294 if not 'mixins' in test:
Stephen Martinis0382bc12018-09-17 22:29:071295 return test
1296
Stephen Martinis2a0667022018-09-25 22:31:141297 if not test_name:
1298 test_name = test.get('test')
1299 if not test_name: # pragma: no cover
1300 # Not the best name, but we should say something.
1301 test_name = str(test)
Stephen Martinisb72f6d22018-10-04 23:29:011302 must_be_list(test['mixins'], 'test', test_name)
1303 for mixin in test['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581304 # We don't bother checking if the given mixin is in remove_mixins here
1305 # since this is already the lowest level, so if a mixin is added here that
1306 # we don't want, we can just delete its entry.
Stephen Martinis0382bc12018-09-17 22:29:071307 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011308 test = self.apply_mixin(self.mixins[mixin], test)
Jeff Yoon67c3e832020-02-08 07:39:381309 del test['mixins']
Stephen Martinis0382bc12018-09-17 22:29:071310 return test
Stephen Martinisb6a50492018-09-12 23:59:321311
Stephen Martinisb72f6d22018-10-04 23:29:011312 def apply_mixin(self, mixin, test):
1313 """Applies a mixin to a test.
Stephen Martinisb6a50492018-09-12 23:59:321314
Stephen Martinis0382bc12018-09-17 22:29:071315 Mixins will not override an existing key. This is to ensure exceptions can
1316 override a setting a mixin applies.
1317
Stephen Martinisb72f6d22018-10-04 23:29:011318 Swarming dimensions are handled in a special way. Instead of specifying
Stephen Martinisb6a50492018-09-12 23:59:321319 'dimension_sets', which is how normal test suites specify their dimensions,
1320 you specify a 'dimensions' key, which maps to a dictionary. This dictionary
1321 is then applied to every dimension set in the test.
Stephen Martinisb72f6d22018-10-04 23:29:011322
Stephen Martinisb6a50492018-09-12 23:59:321323 """
1324 new_test = copy.deepcopy(test)
1325 mixin = copy.deepcopy(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011326 if 'swarming' in mixin:
1327 swarming_mixin = mixin['swarming']
1328 new_test.setdefault('swarming', {})
Brian Sheedycae63b22020-06-10 22:52:111329 # Copy over any explicit dimension sets first so that they will be updated
1330 # by any subsequent 'dimensions' entries.
1331 if 'dimension_sets' in swarming_mixin:
1332 existing_dimension_sets = new_test['swarming'].setdefault(
1333 'dimension_sets', [])
1334 # Appending to the existing list could potentially result in different
1335 # behavior depending on the order the mixins were applied, but that's
1336 # already the case for other parts of mixins, so trust that the user
1337 # will verify that the generated output is correct before submitting.
1338 for dimension_set in swarming_mixin['dimension_sets']:
1339 if dimension_set not in existing_dimension_sets:
1340 existing_dimension_sets.append(dimension_set)
1341 del swarming_mixin['dimension_sets']
Stephen Martinisb72f6d22018-10-04 23:29:011342 if 'dimensions' in swarming_mixin:
1343 new_test['swarming'].setdefault('dimension_sets', [{}])
1344 for dimension_set in new_test['swarming']['dimension_sets']:
1345 dimension_set.update(swarming_mixin['dimensions'])
1346 del swarming_mixin['dimensions']
Stephen Martinisb72f6d22018-10-04 23:29:011347 # python dict update doesn't do recursion at all. Just hard code the
1348 # nested update we need (mixin['swarming'] shouldn't clobber
1349 # test['swarming'], but should update it).
1350 new_test['swarming'].update(swarming_mixin)
1351 del mixin['swarming']
1352
Wezc0e835b702018-10-30 00:38:411353 if '$mixin_append' in mixin:
1354 # Values specified under $mixin_append should be appended to existing
1355 # lists, rather than replacing them.
1356 mixin_append = mixin['$mixin_append']
Zhaoyang Li473dd0ae2021-05-10 18:28:281357
1358 # Append swarming named cache and delete swarming key, since it's under
1359 # another layer of dict.
1360 if 'named_caches' in mixin_append.get('swarming', {}):
1361 new_test['swarming'].setdefault('named_caches', [])
1362 new_test['swarming']['named_caches'].extend(
1363 mixin_append['swarming']['named_caches'])
1364 if len(mixin_append['swarming']) > 1:
1365 raise BBGenErr('Only named_caches is supported under swarming key in '
1366 '$mixin_append, but there are: %s' %
1367 sorted(mixin_append['swarming'].keys()))
1368 del mixin_append['swarming']
Wezc0e835b702018-10-30 00:38:411369 for key in mixin_append:
1370 new_test.setdefault(key, [])
1371 if not isinstance(mixin_append[key], list):
1372 raise BBGenErr(
1373 'Key "' + key + '" in $mixin_append must be a list.')
1374 if not isinstance(new_test[key], list):
1375 raise BBGenErr(
1376 'Cannot apply $mixin_append to non-list "' + key + '".')
1377 new_test[key].extend(mixin_append[key])
1378 if 'args' in mixin_append:
1379 new_test['args'] = self.maybe_fixup_args_array(new_test['args'])
1380 del mixin['$mixin_append']
1381
Stephen Martinisb72f6d22018-10-04 23:29:011382 new_test.update(mixin)
Stephen Martinisb6a50492018-09-12 23:59:321383 return new_test
1384
Greg Gutermanf60eb052020-03-12 17:40:011385 def generate_output_tests(self, waterfall):
1386 """Generates the tests for a waterfall.
1387
1388 Args:
1389 waterfall: a dictionary parsed from a master pyl file
1390 Returns:
1391 A dictionary mapping builders to test specs
1392 """
1393 return {
Jamie Madillcf4f8c72021-05-20 19:24:231394 name: self.get_tests_for_config(waterfall, name, config)
1395 for name, config in waterfall['machines'].items()
Greg Gutermanf60eb052020-03-12 17:40:011396 }
1397
1398 def get_tests_for_config(self, waterfall, name, config):
Greg Guterman5c6144152020-02-28 20:08:531399 generator_map = self.get_test_generator_map()
1400 test_type_remapper = self.get_test_type_remapper()
Kenneth Russelleb60cbd22017-12-05 07:54:281401
Greg Gutermanf60eb052020-03-12 17:40:011402 tests = {}
1403 # Copy only well-understood entries in the machine's configuration
1404 # verbatim into the generated JSON.
1405 if 'additional_compile_targets' in config:
1406 tests['additional_compile_targets'] = config[
1407 'additional_compile_targets']
Jamie Madillcf4f8c72021-05-20 19:24:231408 for test_type, input_tests in config.get('test_suites', {}).items():
Greg Gutermanf60eb052020-03-12 17:40:011409 if test_type not in generator_map:
1410 raise self.unknown_test_suite_type(
1411 test_type, name, waterfall['name']) # pragma: no cover
1412 test_generator = generator_map[test_type]
1413 # Let multiple kinds of generators generate the same kinds
1414 # of tests. For example, gpu_telemetry_tests are a
1415 # specialization of isolated_scripts.
1416 new_tests = test_generator.generate(
1417 waterfall, name, config, input_tests)
1418 remapped_test_type = test_type_remapper.get(test_type, test_type)
1419 tests[remapped_test_type] = test_generator.sort(
1420 tests.get(remapped_test_type, []) + new_tests)
1421
1422 return tests
1423
1424 def jsonify(self, all_tests):
1425 return json.dumps(
1426 all_tests, indent=2, separators=(',', ': '),
1427 sort_keys=True) + '\n'
1428
1429 def generate_outputs(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281430 self.load_configuration_files()
1431 self.resolve_configuration_files()
1432 filters = self.args.waterfall_filters
Greg Gutermanf60eb052020-03-12 17:40:011433 result = collections.defaultdict(dict)
1434
Dirk Pranke6269d302020-10-01 00:14:391435 required_fields = ('name',)
Greg Gutermanf60eb052020-03-12 17:40:011436 for waterfall in self.waterfalls:
1437 for field in required_fields:
1438 # Verify required fields
1439 if field not in waterfall:
1440 raise BBGenErr("Waterfall %s has no %s" % (waterfall['name'], field))
1441
1442 # Handle filter flag, if specified
1443 if filters and waterfall['name'] not in filters:
1444 continue
1445
1446 # Join config files and hardcoded values together
1447 all_tests = self.generate_output_tests(waterfall)
1448 result[waterfall['name']] = all_tests
1449
Greg Gutermanf60eb052020-03-12 17:40:011450 # Add do not edit warning
1451 for tests in result.values():
1452 tests['AAAAA1 AUTOGENERATED FILE DO NOT EDIT'] = {}
1453 tests['AAAAA2 See generate_buildbot_json.py to make changes'] = {}
1454
1455 return result
1456
1457 def write_json_result(self, result): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281458 suffix = '.json'
1459 if self.args.new_files:
1460 suffix = '.new' + suffix
Greg Gutermanf60eb052020-03-12 17:40:011461
1462 for filename, contents in result.items():
1463 jsonstr = self.jsonify(contents)
1464 self.write_file(self.pyl_file_path(filename + suffix), jsonstr)
Kenneth Russelleb60cbd22017-12-05 07:54:281465
Nico Weberd18b8962018-05-16 19:39:381466 def get_valid_bot_names(self):
Ben Joyce2f48b6942020-11-10 21:22:371467 # Extract bot names from infra/config/generated/luci-milo.cfg.
Stephen Martinis26627cf2018-12-19 01:51:421468 # NOTE: This reference can cause issues; if a file changes there, the
1469 # presubmit here won't be run by default. A manually maintained list there
1470 # tries to run presubmit here when luci-milo.cfg is changed. If any other
1471 # references to configs outside of this directory are added, please change
1472 # their presubmit to run `generate_buildbot_json.py -c`, so that the tree
1473 # never ends up in an invalid state.
Garrett Beaty4f3e9212020-06-25 20:21:491474
Garrett Beaty7e866fc2021-06-16 14:12:101475 # Get the generated project.pyl so we can check if we should be enforcing
1476 # that the specs are for builders that actually exist
1477 # If not, return None to indicate that we won't enforce that builders in
1478 # waterfalls.pyl are defined in LUCI
Garrett Beaty4f3e9212020-06-25 20:21:491479 project_pyl_path = os.path.join(self.args.infra_config_dir, 'generated',
1480 'project.pyl')
1481 if os.path.exists(project_pyl_path):
1482 settings = ast.literal_eval(self.read_file(project_pyl_path))
1483 if not settings.get('validate_source_side_specs_have_builder', True):
1484 return None
1485
Nico Weberd18b8962018-05-16 19:39:381486 bot_names = set()
Garrett Beatyd5ca75962020-05-07 16:58:311487 milo_configs = glob.glob(
1488 os.path.join(self.args.infra_config_dir, 'generated', 'luci-milo*.cfg'))
John Budorickc12abd12018-08-14 19:37:431489 for c in milo_configs:
1490 for l in self.read_file(c).splitlines():
1491 if (not 'name: "buildbucket/luci.chromium.' in l and
Garrett Beatyd5ca75962020-05-07 16:58:311492 not 'name: "buildbucket/luci.chrome.' in l):
John Budorickc12abd12018-08-14 19:37:431493 continue
1494 # l looks like
1495 # `name: "buildbucket/luci.chromium.try/win_chromium_dbg_ng"`
1496 # Extract win_chromium_dbg_ng part.
1497 bot_names.add(l[l.rindex('/') + 1:l.rindex('"')])
Nico Weberd18b8962018-05-16 19:39:381498 return bot_names
1499
Ben Pastene9a010082019-09-25 20:41:371500 def get_builders_that_do_not_actually_exist(self):
Kenneth Russell8a386d42018-06-02 09:48:011501 # Some of the bots on the chromium.gpu.fyi waterfall in particular
1502 # are defined only to be mirrored into trybots, and don't actually
1503 # exist on any of the waterfalls or consoles.
1504 return [
Yuke Liao8373de52020-08-14 18:30:541505 'GPU FYI Fuchsia Builder',
1506 'ANGLE GPU Android Release (Nexus 5X)',
1507 'ANGLE GPU Linux Release (Intel HD 630)',
1508 'ANGLE GPU Linux Release (NVIDIA)',
Yuke Liao8373de52020-08-14 18:30:541509 'Optional Android Release (Nexus 5X)',
Brian Sheedy9584d812021-05-26 02:07:251510 'Optional Android Release (Pixel 4)',
Yuke Liao8373de52020-08-14 18:30:541511 'Optional Linux Release (Intel HD 630)',
1512 'Optional Linux Release (NVIDIA)',
1513 'Optional Mac Release (Intel)',
1514 'Optional Mac Retina Release (AMD)',
1515 'Optional Mac Retina Release (NVIDIA)',
1516 'Optional Win10 x64 Release (Intel HD 630)',
1517 'Optional Win10 x64 Release (NVIDIA)',
Yuke Liao8373de52020-08-14 18:30:541518 # chromium.chromiumos
1519 'linux-lacros-rel',
1520 # chromium.fyi
1521 'linux-blink-rel-dummy',
1522 'linux-blink-optional-highdpi-rel-dummy',
1523 'mac10.12-blink-rel-dummy',
1524 'mac10.13-blink-rel-dummy',
1525 'mac10.14-blink-rel-dummy',
1526 'mac10.15-blink-rel-dummy',
Stephanie Kim7fbfd912020-08-21 21:11:001527 'mac11.0-blink-rel-dummy',
Yuke Liao8373de52020-08-14 18:30:541528 'win7-blink-rel-dummy',
1529 'win10-blink-rel-dummy',
1530 'WebKit Linux composite_after_paint Dummy Builder',
1531 'WebKit Linux layout_ng_disabled Builder',
1532 # chromium, due to https://crbug.com/878915
1533 'win-dbg',
1534 'win32-dbg',
1535 'win-archive-dbg',
1536 'win32-archive-dbg',
Garrett Beatyad7bb772021-02-22 17:34:221537 # New LTC isn't created when LTC becomes LTS, so these builders can go
1538 # away
1539 "chromeos-arm-generic-ltc",
1540 "chromeos-betty-pi-arc-chrome-ltc",
1541 "chromeos-eve-chrome-ltc",
1542 "chromeos-kevin-chrome-ltc",
1543 "linux-chromeos-ltc",
1544 "linux64-ltc",
Jacob Kopczynskif4538312020-11-09 23:35:451545 # TODO(https://crbug.com/1127088): remove once LTS version has been set
1546 "chromeos-arm-generic-lts",
1547 "chromeos-betty-pi-arc-chrome-lts",
1548 "chromeos-eve-chrome-lts",
1549 "chromeos-kevin-chrome-lts",
1550 "linux-chromeos-lts",
1551 "linux64-lts",
Stephanie Kim107c1b0e2020-11-18 21:49:411552 # TODO crbug.com/1143924: Remove once experimentation is complete
1553 'Linux Builder Robocrop',
1554 'Linux Tests Robocrop',
Kenneth Russell8a386d42018-06-02 09:48:011555 ]
1556
Ben Pastene9a010082019-09-25 20:41:371557 def get_internal_waterfalls(self):
1558 # Similar to get_builders_that_do_not_actually_exist above, but for
1559 # waterfalls defined in internal configs.
Ben Pastenec7f5c472020-09-18 19:35:471560 return ['chrome', 'chrome.pgo', 'internal.chromeos.fyi', 'internal.soda']
Ben Pastene9a010082019-09-25 20:41:371561
Stephen Martinisf83893722018-09-19 00:02:181562 def check_input_file_consistency(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201563 self.check_input_files_sorting(verbose)
1564
Kenneth Russelleb60cbd22017-12-05 07:54:281565 self.load_configuration_files()
Jeff Yoon8154e582019-12-03 23:30:011566 self.check_composition_type_test_suites('compound_suites')
Jeff Yoon67c3e832020-02-08 07:39:381567 self.check_composition_type_test_suites('matrix_compound_suites',
1568 [check_matrix_identifier])
Chan Lia3ad1502020-04-28 05:32:111569 self.resolve_test_id_prefixes()
Stephen Martinis54d64ad2018-09-21 22:16:201570 self.flatten_test_suites()
Nico Weberd18b8962018-05-16 19:39:381571
1572 # All bots should exist.
1573 bot_names = self.get_valid_bot_names()
Ben Pastene9a010082019-09-25 20:41:371574 builders_that_dont_exist = self.get_builders_that_do_not_actually_exist()
Garrett Beaty2a02de3c2020-05-15 13:57:351575 if bot_names is not None:
1576 internal_waterfalls = self.get_internal_waterfalls()
1577 for waterfall in self.waterfalls:
1578 # TODO(crbug.com/991417): Remove the need for this exception.
1579 if waterfall['name'] in internal_waterfalls:
Kenneth Russell8a386d42018-06-02 09:48:011580 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351581 for bot_name in waterfall['machines']:
1582 if bot_name in builders_that_dont_exist:
Kenneth Russell78fd8702018-05-17 01:15:521583 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351584 if bot_name not in bot_names:
1585 if waterfall['name'] in ['client.v8.chromium', 'client.v8.fyi']:
1586 # TODO(thakis): Remove this once these bots move to luci.
1587 continue # pragma: no cover
1588 if waterfall['name'] in ['tryserver.webrtc',
1589 'webrtc.chromium.fyi.experimental']:
1590 # These waterfalls have their bot configs in a different repo.
1591 # so we don't know about their bot names.
1592 continue # pragma: no cover
1593 if waterfall['name'] in ['client.devtools-frontend.integration',
1594 'tryserver.devtools-frontend',
1595 'chromium.devtools-frontend']:
1596 continue # pragma: no cover
Garrett Beaty48d261a2020-09-17 22:11:201597 if waterfall['name'] in ['client.openscreen.chromium']:
1598 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351599 raise self.unknown_bot(bot_name, waterfall['name'])
Nico Weberd18b8962018-05-16 19:39:381600
Kenneth Russelleb60cbd22017-12-05 07:54:281601 # All test suites must be referenced.
1602 suites_seen = set()
1603 generator_map = self.get_test_generator_map()
1604 for waterfall in self.waterfalls:
Jamie Madillcf4f8c72021-05-20 19:24:231605 for bot_name, tester in waterfall['machines'].items():
1606 for suite_type, suite in tester.get('test_suites', {}).items():
Kenneth Russelleb60cbd22017-12-05 07:54:281607 if suite_type not in generator_map:
1608 raise self.unknown_test_suite_type(suite_type, bot_name,
1609 waterfall['name'])
1610 if suite not in self.test_suites:
1611 raise self.unknown_test_suite(suite, bot_name, waterfall['name'])
1612 suites_seen.add(suite)
1613 # Since we didn't resolve the configuration files, this set
1614 # includes both composition test suites and regular ones.
1615 resolved_suites = set()
1616 for suite_name in suites_seen:
1617 suite = self.test_suites[suite_name]
Jeff Yoon8154e582019-12-03 23:30:011618 for sub_suite in suite:
1619 resolved_suites.add(sub_suite)
Kenneth Russelleb60cbd22017-12-05 07:54:281620 resolved_suites.add(suite_name)
1621 # At this point, every key in test_suites.pyl should be referenced.
1622 missing_suites = set(self.test_suites.keys()) - resolved_suites
1623 if missing_suites:
1624 raise BBGenErr('The following test suites were unreferenced by bots on '
1625 'the waterfalls: ' + str(missing_suites))
1626
1627 # All test suite exceptions must refer to bots on the waterfall.
1628 all_bots = set()
1629 missing_bots = set()
1630 for waterfall in self.waterfalls:
Jamie Madillcf4f8c72021-05-20 19:24:231631 for bot_name, tester in waterfall['machines'].items():
Kenneth Russelleb60cbd22017-12-05 07:54:281632 all_bots.add(bot_name)
Kenneth Russell8ceeabf2017-12-11 17:53:281633 # In order to disambiguate between bots with the same name on
1634 # different waterfalls, support has been added to various
1635 # exceptions for concatenating the waterfall name after the bot
1636 # name.
1637 all_bots.add(bot_name + ' ' + waterfall['name'])
Jamie Madillcf4f8c72021-05-20 19:24:231638 for exception in self.exceptions.values():
Nico Weberd18b8962018-05-16 19:39:381639 removals = (exception.get('remove_from', []) +
1640 exception.get('remove_gtest_from', []) +
Jamie Madillcf4f8c72021-05-20 19:24:231641 list(exception.get('modifications', {}).keys()))
Nico Weberd18b8962018-05-16 19:39:381642 for removal in removals:
Kenneth Russelleb60cbd22017-12-05 07:54:281643 if removal not in all_bots:
1644 missing_bots.add(removal)
Stephen Martiniscc70c962018-07-31 21:22:411645
Ben Pastene9a010082019-09-25 20:41:371646 missing_bots = missing_bots - set(builders_that_dont_exist)
Kenneth Russelleb60cbd22017-12-05 07:54:281647 if missing_bots:
1648 raise BBGenErr('The following nonexistent machines were referenced in '
1649 'the test suite exceptions: ' + str(missing_bots))
1650
Stephen Martinis0382bc12018-09-17 22:29:071651 # All mixins must be referenced
1652 seen_mixins = set()
1653 for waterfall in self.waterfalls:
Stephen Martinisb72f6d22018-10-04 23:29:011654 seen_mixins = seen_mixins.union(waterfall.get('mixins', set()))
Jamie Madillcf4f8c72021-05-20 19:24:231655 for bot_name, tester in waterfall['machines'].items():
Stephen Martinisb72f6d22018-10-04 23:29:011656 seen_mixins = seen_mixins.union(tester.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071657 for suite in self.test_suites.values():
1658 if isinstance(suite, list):
1659 # Don't care about this, it's a composition, which shouldn't include a
1660 # swarming mixin.
1661 continue
1662
1663 for test in suite.values():
Dirk Pranke0e879b22020-07-16 23:53:561664 assert isinstance(test, dict)
Stephen Martinisb72f6d22018-10-04 23:29:011665 seen_mixins = seen_mixins.union(test.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071666
Zhaoyang Li9da047d52021-05-10 21:31:441667 for variant in self.variants:
1668 # Unpack the variant from variants.pyl if it's string based.
1669 if isinstance(variant, str):
1670 variant = self.variants[variant]
1671 seen_mixins = seen_mixins.union(variant.get('mixins', set()))
1672
Stephen Martinisb72f6d22018-10-04 23:29:011673 missing_mixins = set(self.mixins.keys()) - seen_mixins
Stephen Martinis0382bc12018-09-17 22:29:071674 if missing_mixins:
1675 raise BBGenErr('The following mixins are unreferenced: %s. They must be'
1676 ' referenced in a waterfall, machine, or test suite.' % (
1677 str(missing_mixins)))
1678
Jeff Yoonda581c32020-03-06 03:56:051679 # All variant references must be referenced
1680 seen_variants = set()
1681 for suite in self.test_suites.values():
1682 if isinstance(suite, list):
1683 continue
1684
1685 for test in suite.values():
1686 if isinstance(test, dict):
1687 for variant in test.get('variants', []):
1688 if isinstance(variant, str):
1689 seen_variants.add(variant)
1690
1691 missing_variants = set(self.variants.keys()) - seen_variants
1692 if missing_variants:
1693 raise BBGenErr('The following variants were unreferenced: %s. They must '
1694 'be referenced in a matrix test suite under the variants '
1695 'key.' % str(missing_variants))
1696
Stephen Martinis54d64ad2018-09-21 22:16:201697
1698 def type_assert(self, node, typ, filename, verbose=False):
1699 """Asserts that the Python AST node |node| is of type |typ|.
1700
1701 If verbose is set, it prints out some helpful context lines, showing where
1702 exactly the error occurred in the file.
1703 """
1704 if not isinstance(node, typ):
1705 if verbose:
1706 lines = [""] + self.read_file(filename).splitlines()
1707
1708 context = 2
1709 lines_start = max(node.lineno - context, 0)
1710 # Add one to include the last line
1711 lines_end = min(node.lineno + context, len(lines)) + 1
1712 lines = (
1713 ['== %s ==\n' % filename] +
1714 ["<snip>\n"] +
1715 ['%d %s' % (lines_start + i, line) for i, line in enumerate(
1716 lines[lines_start:lines_start + context])] +
1717 ['-' * 80 + '\n'] +
1718 ['%d %s' % (node.lineno, lines[node.lineno])] +
1719 ['-' * (node.col_offset + 3) + '^' + '-' * (
1720 80 - node.col_offset - 4) + '\n'] +
1721 ['%d %s' % (node.lineno + 1 + i, line) for i, line in enumerate(
1722 lines[node.lineno + 1:lines_end])] +
1723 ["<snip>\n"]
1724 )
1725 # Print out a useful message when a type assertion fails.
1726 for l in lines:
1727 self.print_line(l.strip())
1728
1729 node_dumped = ast.dump(node, annotate_fields=False)
1730 # If the node is huge, truncate it so everything fits in a terminal
1731 # window.
1732 if len(node_dumped) > 60: # pragma: no cover
1733 node_dumped = node_dumped[:30] + ' <SNIP> ' + node_dumped[-30:]
1734 raise BBGenErr(
1735 'Invalid .pyl file %r. Python AST node %r on line %s expected to'
1736 ' be %s, is %s' % (
1737 filename, node_dumped,
1738 node.lineno, typ, type(node)))
1739
Stephen Martinis5bef0fc2020-01-06 22:47:531740 def check_ast_list_formatted(self, keys, filename, verbose,
Stephen Martinis1384ff92020-01-07 19:52:151741 check_sorting=True):
Stephen Martinis5bef0fc2020-01-06 22:47:531742 """Checks if a list of ast keys are correctly formatted.
Stephen Martinis54d64ad2018-09-21 22:16:201743
Stephen Martinis5bef0fc2020-01-06 22:47:531744 Currently only checks to ensure they're correctly sorted, and that there
1745 are no duplicates.
1746
1747 Args:
1748 keys: An python list of AST nodes.
1749
1750 It's a list of AST nodes instead of a list of strings because
1751 when verbose is set, it tries to print out context of where the
1752 diffs are in the file.
1753 filename: The name of the file this node is from.
1754 verbose: If set, print out diff information about how the keys are
1755 incorrectly formatted.
1756 check_sorting: If true, checks if the list is sorted.
1757 Returns:
1758 If the keys are correctly formatted.
1759 """
1760 if not keys:
1761 return True
1762
1763 assert isinstance(keys[0], ast.Str)
1764
1765 keys_strs = [k.s for k in keys]
1766 # Keys to diff against. Used below.
1767 keys_to_diff_against = None
1768 # If the list is properly formatted.
1769 list_formatted = True
1770
1771 # Duplicates are always bad.
1772 if len(set(keys_strs)) != len(keys_strs):
1773 list_formatted = False
1774 keys_to_diff_against = list(collections.OrderedDict.fromkeys(keys_strs))
1775
1776 if check_sorting and sorted(keys_strs) != keys_strs:
1777 list_formatted = False
1778 if list_formatted:
1779 return True
1780
1781 if verbose:
1782 line_num = keys[0].lineno
1783 keys = [k.s for k in keys]
1784 if check_sorting:
1785 # If we have duplicates, sorting this will take care of it anyways.
1786 keys_to_diff_against = sorted(set(keys))
1787 # else, keys_to_diff_against is set above already
1788
1789 self.print_line('=' * 80)
1790 self.print_line('(First line of keys is %s)' % line_num)
1791 for line in difflib.context_diff(
1792 keys, keys_to_diff_against,
1793 fromfile='current (%r)' % filename, tofile='sorted', lineterm=''):
1794 self.print_line(line)
1795 self.print_line('=' * 80)
1796
1797 return False
1798
Stephen Martinis1384ff92020-01-07 19:52:151799 def check_ast_dict_formatted(self, node, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531800 """Checks if an ast dictionary's keys are correctly formatted.
1801
1802 Just a simple wrapper around check_ast_list_formatted.
1803 Args:
1804 node: An AST node. Assumed to be a dictionary.
1805 filename: The name of the file this node is from.
1806 verbose: If set, print out diff information about how the keys are
1807 incorrectly formatted.
1808 check_sorting: If true, checks if the list is sorted.
1809 Returns:
1810 If the dictionary is correctly formatted.
1811 """
Stephen Martinis54d64ad2018-09-21 22:16:201812 keys = []
1813 # The keys of this dict are ordered as ordered in the file; normal python
1814 # dictionary keys are given an arbitrary order, but since we parsed the
1815 # file itself, the order as given in the file is preserved.
1816 for key in node.keys:
1817 self.type_assert(key, ast.Str, filename, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531818 keys.append(key)
Stephen Martinis54d64ad2018-09-21 22:16:201819
Stephen Martinis1384ff92020-01-07 19:52:151820 return self.check_ast_list_formatted(keys, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181821
1822 def check_input_files_sorting(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201823 # TODO(https://crbug.com/886993): Add the ability for this script to
1824 # actually format the files, rather than just complain if they're
1825 # incorrectly formatted.
1826 bad_files = set()
Stephen Martinis5bef0fc2020-01-06 22:47:531827 def parse_file(filename):
1828 """Parses and validates a .pyl file.
Stephen Martinis54d64ad2018-09-21 22:16:201829
Stephen Martinis5bef0fc2020-01-06 22:47:531830 Returns an AST node representing the value in the pyl file."""
Stephen Martinisf83893722018-09-19 00:02:181831 parsed = ast.parse(self.read_file(self.pyl_file_path(filename)))
1832
Stephen Martinisf83893722018-09-19 00:02:181833 # Must be a module.
Stephen Martinis54d64ad2018-09-21 22:16:201834 self.type_assert(parsed, ast.Module, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181835 module = parsed.body
1836
1837 # Only one expression in the module.
Stephen Martinis54d64ad2018-09-21 22:16:201838 self.type_assert(module, list, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181839 if len(module) != 1: # pragma: no cover
1840 raise BBGenErr('Invalid .pyl file %s' % filename)
1841 expr = module[0]
Stephen Martinis54d64ad2018-09-21 22:16:201842 self.type_assert(expr, ast.Expr, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181843
Stephen Martinis5bef0fc2020-01-06 22:47:531844 return expr.value
1845
1846 # Handle this separately
1847 filename = 'waterfalls.pyl'
1848 value = parse_file(filename)
1849 # Value should be a list.
1850 self.type_assert(value, ast.List, filename, verbose)
1851
1852 keys = []
1853 for val in value.elts:
1854 self.type_assert(val, ast.Dict, filename, verbose)
1855 waterfall_name = None
1856 for key, val in zip(val.keys, val.values):
1857 self.type_assert(key, ast.Str, filename, verbose)
1858 if key.s == 'machines':
1859 if not self.check_ast_dict_formatted(val, filename, verbose):
1860 bad_files.add(filename)
1861
1862 if key.s == "name":
1863 self.type_assert(val, ast.Str, filename, verbose)
1864 waterfall_name = val
1865 assert waterfall_name
1866 keys.append(waterfall_name)
1867
Stephen Martinis1384ff92020-01-07 19:52:151868 if not self.check_ast_list_formatted(keys, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531869 bad_files.add(filename)
1870
1871 for filename in (
1872 'mixins.pyl',
1873 'test_suites.pyl',
1874 'test_suite_exceptions.pyl',
1875 ):
1876 value = parse_file(filename)
Stephen Martinisf83893722018-09-19 00:02:181877 # Value should be a dictionary.
Stephen Martinis54d64ad2018-09-21 22:16:201878 self.type_assert(value, ast.Dict, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181879
Stephen Martinis5bef0fc2020-01-06 22:47:531880 if not self.check_ast_dict_formatted(
1881 value, filename, verbose):
1882 bad_files.add(filename)
1883
Stephen Martinis54d64ad2018-09-21 22:16:201884 if filename == 'test_suites.pyl':
Jeff Yoon8154e582019-12-03 23:30:011885 expected_keys = ['basic_suites',
1886 'compound_suites',
1887 'matrix_compound_suites']
Stephen Martinis54d64ad2018-09-21 22:16:201888 actual_keys = [node.s for node in value.keys]
1889 assert all(key in expected_keys for key in actual_keys), (
1890 'Invalid %r file; expected keys %r, got %r' % (
1891 filename, expected_keys, actual_keys))
1892 suite_dicts = [node for node in value.values]
1893 # Only two keys should mean only 1 or 2 values
Jeff Yoon8154e582019-12-03 23:30:011894 assert len(suite_dicts) <= 3
Stephen Martinis54d64ad2018-09-21 22:16:201895 for suite_group in suite_dicts:
Stephen Martinis5bef0fc2020-01-06 22:47:531896 if not self.check_ast_dict_formatted(
Stephen Martinis54d64ad2018-09-21 22:16:201897 suite_group, filename, verbose):
1898 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181899
Stephen Martinis5bef0fc2020-01-06 22:47:531900 for key, suite in zip(value.keys, value.values):
1901 # The compound suites are checked in
1902 # 'check_composition_type_test_suites()'
1903 if key.s == 'basic_suites':
1904 for group in suite.values:
Stephen Martinis1384ff92020-01-07 19:52:151905 if not self.check_ast_dict_formatted(group, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531906 bad_files.add(filename)
1907 break
Stephen Martinis54d64ad2018-09-21 22:16:201908
Stephen Martinis5bef0fc2020-01-06 22:47:531909 elif filename == 'test_suite_exceptions.pyl':
1910 # Check the values for each test.
1911 for test in value.values:
1912 for kind, node in zip(test.keys, test.values):
1913 if isinstance(node, ast.Dict):
Stephen Martinis1384ff92020-01-07 19:52:151914 if not self.check_ast_dict_formatted(node, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531915 bad_files.add(filename)
1916 elif kind.s == 'remove_from':
1917 # Don't care about sorting; these are usually grouped, since the
1918 # same bug can affect multiple builders. Do want to make sure
1919 # there aren't duplicates.
1920 if not self.check_ast_list_formatted(node.elts, filename, verbose,
1921 check_sorting=False):
1922 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181923
1924 if bad_files:
1925 raise BBGenErr(
Stephen Martinis54d64ad2018-09-21 22:16:201926 'The following files have invalid keys: %s\n. They are either '
Stephen Martinis5bef0fc2020-01-06 22:47:531927 'unsorted, or have duplicates. Re-run this with --verbose to see '
1928 'more details.' % ', '.join(bad_files))
Stephen Martinisf83893722018-09-19 00:02:181929
Kenneth Russelleb60cbd22017-12-05 07:54:281930 def check_output_file_consistency(self, verbose=False):
1931 self.load_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011932 # All waterfalls/bucket .json files must have been written
1933 # by this script already.
Kenneth Russelleb60cbd22017-12-05 07:54:281934 self.resolve_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011935 ungenerated_files = set()
Dirk Pranke772f55f2021-04-28 04:51:161936 outputs = self.generate_outputs()
1937 for filename, expected_contents in outputs.items():
Greg Gutermanf60eb052020-03-12 17:40:011938 expected = self.jsonify(expected_contents)
1939 file_path = filename + '.json'
Zhiling Huangbe008172018-03-08 19:13:111940 current = self.read_file(self.pyl_file_path(file_path))
Kenneth Russelleb60cbd22017-12-05 07:54:281941 if expected != current:
Greg Gutermanf60eb052020-03-12 17:40:011942 ungenerated_files.add(filename)
John Budorick826d5ed2017-12-28 19:27:321943 if verbose: # pragma: no cover
Greg Gutermanf60eb052020-03-12 17:40:011944 self.print_line('File ' + filename +
1945 '.json did not have the following expected '
John Budorick826d5ed2017-12-28 19:27:321946 'contents:')
1947 for line in difflib.unified_diff(
1948 expected.splitlines(),
Stephen Martinis7eb8b612018-09-21 00:17:501949 current.splitlines(),
1950 fromfile='expected', tofile='current'):
1951 self.print_line(line)
Greg Gutermanf60eb052020-03-12 17:40:011952
1953 if ungenerated_files:
1954 raise BBGenErr(
1955 'The following files have not been properly '
1956 'autogenerated by generate_buildbot_json.py: ' +
1957 ', '.join([filename + '.json' for filename in ungenerated_files]))
Kenneth Russelleb60cbd22017-12-05 07:54:281958
Dirk Pranke772f55f2021-04-28 04:51:161959 for builder_group, builders in outputs.items():
1960 for builder, step_types in builders.items():
1961 for step_data in step_types.get('gtest_tests', []):
1962 step_name = step_data.get('name', step_data['test'])
1963 self._check_swarming_config(builder_group, builder, step_name,
1964 step_data)
1965 for step_data in step_types.get('isolated_scripts', []):
1966 step_name = step_data.get('name', step_data['isolate_name'])
1967 self._check_swarming_config(builder_group, builder, step_name,
1968 step_data)
1969
1970 def _check_swarming_config(self, filename, builder, step_name, step_data):
1971 # TODO(crbug.com/1203436): Ensure all swarming tests specify os and cpu, not
1972 # just mac tests.
1973 if ('mac' in builder.lower()
1974 and step_data['swarming']['can_use_on_swarming_builders']):
1975 dimension_sets = step_data['swarming'].get('dimension_sets')
1976 if not dimension_sets:
1977 raise BBGenErr('%s: %s / %s : os and cpu must be specified for mac '
1978 'swarmed tests' % (filename, builder, step_name))
1979 for s in dimension_sets:
1980 if not s.get('os') or not s.get('cpu'):
1981 raise BBGenErr('%s: %s / %s : os and cpu must be specified for mac '
1982 'swarmed tests' % (filename, builder, step_name))
1983
Kenneth Russelleb60cbd22017-12-05 07:54:281984 def check_consistency(self, verbose=False):
Stephen Martinis7eb8b612018-09-21 00:17:501985 self.check_input_file_consistency(verbose) # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281986 self.check_output_file_consistency(verbose) # pragma: no cover
1987
Karen Qiane24b7ee2019-02-12 23:37:061988 def does_test_match(self, test_info, params_dict):
1989 """Checks to see if the test matches the parameters given.
1990
1991 Compares the provided test_info with the params_dict to see
1992 if the bot matches the parameters given. If so, returns True.
1993 Else, returns false.
1994
1995 Args:
1996 test_info (dict): Information about a specific bot provided
1997 in the format shown in waterfalls.pyl
1998 params_dict (dict): Dictionary of parameters and their values
1999 to look for in the bot
2000 Ex: {
2001 'device_os':'android',
2002 '--flag':True,
2003 'mixins': ['mixin1', 'mixin2'],
2004 'ex_key':'ex_value'
2005 }
2006
2007 """
2008 DIMENSION_PARAMS = ['device_os', 'device_type', 'os',
2009 'kvm', 'pool', 'integrity'] # dimension parameters
2010 SWARMING_PARAMS = ['shards', 'hard_timeout', 'idempotent',
2011 'can_use_on_swarming_builders']
2012 for param in params_dict:
2013 # if dimension parameter
2014 if param in DIMENSION_PARAMS or param in SWARMING_PARAMS:
2015 if not 'swarming' in test_info:
2016 return False
2017 swarming = test_info['swarming']
2018 if param in SWARMING_PARAMS:
2019 if not param in swarming:
2020 return False
2021 if not str(swarming[param]) == params_dict[param]:
2022 return False
2023 else:
2024 if not 'dimension_sets' in swarming:
2025 return False
2026 d_set = swarming['dimension_sets']
2027 # only looking at the first dimension set
2028 if not param in d_set[0]:
2029 return False
2030 if not d_set[0][param] == params_dict[param]:
2031 return False
2032
2033 # if flag
2034 elif param.startswith('--'):
2035 if not 'args' in test_info:
2036 return False
2037 if not param in test_info['args']:
2038 return False
2039
2040 # not dimension parameter/flag/mixin
2041 else:
2042 if not param in test_info:
2043 return False
2044 if not test_info[param] == params_dict[param]:
2045 return False
2046 return True
2047 def error_msg(self, msg):
2048 """Prints an error message.
2049
2050 In addition to a catered error message, also prints
2051 out where the user can find more help. Then, program exits.
2052 """
2053 self.print_line(msg + (' If you need more information, ' +
2054 'please run with -h or --help to see valid commands.'))
2055 sys.exit(1)
2056
2057 def find_bots_that_run_test(self, test, bots):
2058 matching_bots = []
2059 for bot in bots:
2060 bot_info = bots[bot]
2061 tests = self.flatten_tests_for_bot(bot_info)
2062 for test_info in tests:
2063 test_name = ""
2064 if 'name' in test_info:
2065 test_name = test_info['name']
2066 elif 'test' in test_info:
2067 test_name = test_info['test']
2068 if not test_name == test:
2069 continue
2070 matching_bots.append(bot)
2071 return matching_bots
2072
2073 def find_tests_with_params(self, tests, params_dict):
2074 matching_tests = []
2075 for test_name in tests:
2076 test_info = tests[test_name]
2077 if not self.does_test_match(test_info, params_dict):
2078 continue
2079 if not test_name in matching_tests:
2080 matching_tests.append(test_name)
2081 return matching_tests
2082
2083 def flatten_waterfalls_for_query(self, waterfalls):
2084 bots = {}
2085 for waterfall in waterfalls:
Greg Gutermanf60eb052020-03-12 17:40:012086 waterfall_tests = self.generate_output_tests(waterfall)
2087 for bot in waterfall_tests:
2088 bot_info = waterfall_tests[bot]
2089 bots[bot] = bot_info
Karen Qiane24b7ee2019-02-12 23:37:062090 return bots
2091
2092 def flatten_tests_for_bot(self, bot_info):
2093 """Returns a list of flattened tests.
2094
2095 Returns a list of tests not grouped by test category
2096 for a specific bot.
2097 """
2098 TEST_CATS = self.get_test_generator_map().keys()
2099 tests = []
2100 for test_cat in TEST_CATS:
2101 if not test_cat in bot_info:
2102 continue
2103 test_cat_tests = bot_info[test_cat]
2104 tests = tests + test_cat_tests
2105 return tests
2106
2107 def flatten_tests_for_query(self, test_suites):
2108 """Returns a flattened dictionary of tests.
2109
2110 Returns a dictionary of tests associate with their
2111 configuration, not grouped by their test suite.
2112 """
2113 tests = {}
Jamie Madillcf4f8c72021-05-20 19:24:232114 for test_suite in test_suites.values():
Karen Qiane24b7ee2019-02-12 23:37:062115 for test in test_suite:
2116 test_info = test_suite[test]
2117 test_name = test
2118 if 'name' in test_info:
2119 test_name = test_info['name']
2120 tests[test_name] = test_info
2121 return tests
2122
2123 def parse_query_filter_params(self, params):
2124 """Parses the filter parameters.
2125
2126 Creates a dictionary from the parameters provided
2127 to filter the bot array.
2128 """
2129 params_dict = {}
2130 for p in params:
2131 # flag
2132 if p.startswith("--"):
2133 params_dict[p] = True
2134 else:
2135 pair = p.split(":")
2136 if len(pair) != 2:
2137 self.error_msg('Invalid command.')
2138 # regular parameters
2139 if pair[1].lower() == "true":
2140 params_dict[pair[0]] = True
2141 elif pair[1].lower() == "false":
2142 params_dict[pair[0]] = False
2143 else:
2144 params_dict[pair[0]] = pair[1]
2145 return params_dict
2146
2147 def get_test_suites_dict(self, bots):
2148 """Returns a dictionary of bots and their tests.
2149
2150 Returns a dictionary of bots and a list of their associated tests.
2151 """
2152 test_suite_dict = dict()
2153 for bot in bots:
2154 bot_info = bots[bot]
2155 tests = self.flatten_tests_for_bot(bot_info)
2156 test_suite_dict[bot] = tests
2157 return test_suite_dict
2158
2159 def output_query_result(self, result, json_file=None):
2160 """Outputs the result of the query.
2161
2162 If a json file parameter name is provided, then
2163 the result is output into the json file. If not,
2164 then the result is printed to the console.
2165 """
2166 output = json.dumps(result, indent=2)
2167 if json_file:
2168 self.write_file(json_file, output)
2169 else:
2170 self.print_line(output)
2171 return
2172
2173 def query(self, args):
2174 """Queries tests or bots.
2175
2176 Depending on the arguments provided, outputs a json of
2177 tests or bots matching the appropriate optional parameters provided.
2178 """
2179 # split up query statement
2180 query = args.query.split('/')
2181 self.load_configuration_files()
2182 self.resolve_configuration_files()
2183
2184 # flatten bots json
2185 tests = self.test_suites
2186 bots = self.flatten_waterfalls_for_query(self.waterfalls)
2187
2188 cmd_class = query[0]
2189
2190 # For queries starting with 'bots'
2191 if cmd_class == "bots":
2192 if len(query) == 1:
2193 return self.output_query_result(bots, args.json)
2194 # query with specific parameters
2195 elif len(query) == 2:
2196 if query[1] == 'tests':
2197 test_suites_dict = self.get_test_suites_dict(bots)
2198 return self.output_query_result(test_suites_dict, args.json)
2199 else:
2200 self.error_msg("This query should be in the format: bots/tests.")
2201
2202 else:
2203 self.error_msg("This query should have 0 or 1 '/', found %s instead."
2204 % str(len(query)-1))
2205
2206 # For queries starting with 'bot'
2207 elif cmd_class == "bot":
2208 if not len(query) == 2 and not len(query) == 3:
2209 self.error_msg("Command should have 1 or 2 '/', found %s instead."
2210 % str(len(query)-1))
2211 bot_id = query[1]
2212 if not bot_id in bots:
2213 self.error_msg("No bot named '" + bot_id + "' found.")
2214 bot_info = bots[bot_id]
2215 if len(query) == 2:
2216 return self.output_query_result(bot_info, args.json)
2217 if not query[2] == 'tests':
2218 self.error_msg("The query should be in the format:" +
2219 "bot/<bot-name>/tests.")
2220
2221 bot_tests = self.flatten_tests_for_bot(bot_info)
2222 return self.output_query_result(bot_tests, args.json)
2223
2224 # For queries starting with 'tests'
2225 elif cmd_class == "tests":
2226 if not len(query) == 1 and not len(query) == 2:
2227 self.error_msg("The query should have 0 or 1 '/', found %s instead."
2228 % str(len(query)-1))
2229 flattened_tests = self.flatten_tests_for_query(tests)
2230 if len(query) == 1:
2231 return self.output_query_result(flattened_tests, args.json)
2232
2233 # create params dict
2234 params = query[1].split('&')
2235 params_dict = self.parse_query_filter_params(params)
2236 matching_bots = self.find_tests_with_params(flattened_tests, params_dict)
2237 return self.output_query_result(matching_bots)
2238
2239 # For queries starting with 'test'
2240 elif cmd_class == "test":
2241 if not len(query) == 2 and not len(query) == 3:
2242 self.error_msg("The query should have 1 or 2 '/', found %s instead."
2243 % str(len(query)-1))
2244 test_id = query[1]
2245 if len(query) == 2:
2246 flattened_tests = self.flatten_tests_for_query(tests)
2247 for test in flattened_tests:
2248 if test == test_id:
2249 return self.output_query_result(flattened_tests[test], args.json)
2250 self.error_msg("There is no test named %s." % test_id)
2251 if not query[2] == 'bots':
2252 self.error_msg("The query should be in the format: " +
2253 "test/<test-name>/bots")
2254 bots_for_test = self.find_bots_that_run_test(test_id, bots)
2255 return self.output_query_result(bots_for_test)
2256
2257 else:
2258 self.error_msg("Your command did not match any valid commands." +
2259 "Try starting with 'bots', 'bot', 'tests', or 'test'.")
Kenneth Russelleb60cbd22017-12-05 07:54:282260
Garrett Beaty1afaccc2020-06-25 19:58:152261 def main(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:282262 if self.args.check:
Stephen Martinis7eb8b612018-09-21 00:17:502263 self.check_consistency(verbose=self.args.verbose)
Karen Qiane24b7ee2019-02-12 23:37:062264 elif self.args.query:
2265 self.query(self.args)
Kenneth Russelleb60cbd22017-12-05 07:54:282266 else:
Greg Gutermanf60eb052020-03-12 17:40:012267 self.write_json_result(self.generate_outputs())
Kenneth Russelleb60cbd22017-12-05 07:54:282268 return 0
2269
2270if __name__ == "__main__": # pragma: no cover
Garrett Beaty1afaccc2020-06-25 19:58:152271 generator = BBJSONGenerator(BBJSONGenerator.parse_args(sys.argv[1:]))
2272 sys.exit(generator.main())