blob: 176c931ba319b137d455a40e3b518a601e907710 [file] [log] [blame]
Joshua Hood3455e1352022-03-03 23:23:591#!/usr/bin/env vpython3
Avi Drissmandfd880852022-09-15 20:11:092# Copyright 2016 The Chromium Authors
Kenneth Russelleb60cbd22017-12-05 07:54:283# 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
Garrett Beatyd5ca75962020-05-07 16:58:3115import glob
Kenneth Russell8ceeabf2017-12-11 17:53:2816import itertools
Kenneth Russelleb60cbd22017-12-05 07:54:2817import json
18import os
Kenneth Russelleb60cbd22017-12-05 07:54:2819import string
20import sys
21
Brian Sheedya31578e2020-05-18 20:24:3622import buildbot_json_magic_substitutions as magic_substitutions
23
Joshua Hood56c673c2022-03-02 20:29:3324# pylint: disable=super-with-arguments,useless-super-delegation
25
Kenneth Russelleb60cbd22017-12-05 07:54:2826THIS_DIR = os.path.dirname(os.path.abspath(__file__))
27
Brian Sheedyf74819b2021-06-04 01:38:3828BROWSER_CONFIG_TO_TARGET_SUFFIX_MAP = {
29 'android-chromium': '_android_chrome',
30 'android-chromium-monochrome': '_android_monochrome',
Brian Sheedyf74819b2021-06-04 01:38:3831 'android-webview': '_android_webview',
32}
33
Kenneth Russelleb60cbd22017-12-05 07:54:2834
35class BBGenErr(Exception):
Nico Weber79dc5f6852018-07-13 19:38:4936 def __init__(self, message):
37 super(BBGenErr, self).__init__(message)
Kenneth Russelleb60cbd22017-12-05 07:54:2838
39
Joshua Hood56c673c2022-03-02 20:29:3340class BaseGenerator(object): # pylint: disable=useless-object-inheritance
Kenneth Russelleb60cbd22017-12-05 07:54:2841 def __init__(self, bb_gen):
42 self.bb_gen = bb_gen
43
Kenneth Russell8ceeabf2017-12-11 17:53:2844 def generate(self, waterfall, tester_name, tester_config, input_tests):
Garrett Beatyffe83c4f2023-09-08 19:07:3745 raise NotImplementedError() # pragma: no cover
Kenneth Russell8ceeabf2017-12-11 17:53:2846
47
Kenneth Russell8a386d42018-06-02 09:48:0148class GPUTelemetryTestGenerator(BaseGenerator):
Xinan Linedcf05b32023-10-19 23:13:5049 def __init__(self,
50 bb_gen,
51 is_android_webview=False,
52 is_cast_streaming=False,
53 is_skylab=False):
Kenneth Russell8a386d42018-06-02 09:48:0154 super(GPUTelemetryTestGenerator, self).__init__(bb_gen)
Bo Liu555a0f92019-03-29 12:11:5655 self._is_android_webview = is_android_webview
Fabrice de Ganscbd655f2022-08-04 20:15:3056 self._is_cast_streaming = is_cast_streaming
Xinan Linedcf05b32023-10-19 23:13:5057 self._is_skylab = is_skylab
Kenneth Russell8a386d42018-06-02 09:48:0158
59 def generate(self, waterfall, tester_name, tester_config, input_tests):
60 isolated_scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:2361 for test_name, test_config in sorted(input_tests.items()):
Ben Pastene8e7eb2652022-04-29 19:44:3162 # Variants allow more than one definition for a given test, and is defined
63 # in array format from resolve_variants().
64 if not isinstance(test_config, list):
65 test_config = [test_config]
66
67 for config in test_config:
Xinan Linedcf05b32023-10-19 23:13:5068 test = self.bb_gen.generate_gpu_telemetry_test(
69 waterfall, tester_name, tester_config, test_name, config,
70 self._is_android_webview, self._is_cast_streaming, self._is_skylab)
Ben Pastene8e7eb2652022-04-29 19:44:3171 if test:
72 isolated_scripts.append(test)
73
Kenneth Russell8a386d42018-06-02 09:48:0174 return isolated_scripts
75
Kenneth Russell8a386d42018-06-02 09:48:0176
Brian Sheedyb6491ba2022-09-26 20:49:4977class SkylabGPUTelemetryTestGenerator(GPUTelemetryTestGenerator):
Xinan Linedcf05b32023-10-19 23:13:5078 def __init__(self, bb_gen):
79 super(SkylabGPUTelemetryTestGenerator, self).__init__(bb_gen,
80 is_skylab=True)
81
Brian Sheedyb6491ba2022-09-26 20:49:4982 def generate(self, *args, **kwargs):
83 # This should be identical to a regular GPU Telemetry test, but with any
84 # swarming arguments removed.
85 isolated_scripts = super(SkylabGPUTelemetryTestGenerator,
86 self).generate(*args, **kwargs)
87 for test in isolated_scripts:
Xinan Lind9b1d2e72022-11-14 20:57:0288 # chromium_GPU is the Autotest wrapper created for browser GPU tests
89 # run in Skylab.
Xinan Lin1f28a0d2023-03-13 17:39:4190 test['autotest_name'] = 'chromium_Graphics'
Xinan Lind9b1d2e72022-11-14 20:57:0291 # As of 22Q4, Skylab tests are running on a CrOS flavored Autotest
92 # framework and it does not support the sub-args like
93 # extra-browser-args. So we have to pop it out and create a new
94 # key for it. See crrev.com/c/3965359 for details.
95 for idx, arg in enumerate(test.get('args', [])):
96 if '--extra-browser-args' in arg:
97 test['args'].pop(idx)
98 test['extra_browser_args'] = arg.replace('--extra-browser-args=', '')
99 break
Brian Sheedyb6491ba2022-09-26 20:49:49100 return isolated_scripts
101
102
Kenneth Russelleb60cbd22017-12-05 07:54:28103class GTestGenerator(BaseGenerator):
104 def __init__(self, bb_gen):
105 super(GTestGenerator, self).__init__(bb_gen)
106
Kenneth Russell8ceeabf2017-12-11 17:53:28107 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28108 # The relative ordering of some of the tests is important to
109 # minimize differences compared to the handwritten JSON files, since
110 # Python's sorts are stable and there are some tests with the same
111 # key (see gles2_conform_d3d9_test and similar variants). Avoid
112 # losing the order by avoiding coalescing the dictionaries into one.
113 gtests = []
Jamie Madillcf4f8c72021-05-20 19:24:23114 for test_name, test_config in sorted(input_tests.items()):
Jeff Yoon67c3e832020-02-08 07:39:38115 # Variants allow more than one definition for a given test, and is defined
116 # in array format from resolve_variants().
117 if not isinstance(test_config, list):
118 test_config = [test_config]
119
120 for config in test_config:
121 test = self.bb_gen.generate_gtest(
122 waterfall, tester_name, tester_config, test_name, config)
123 if test:
124 # generate_gtest may veto the test generation on this tester.
125 gtests.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28126 return gtests
127
Kenneth Russelleb60cbd22017-12-05 07:54:28128
129class IsolatedScriptTestGenerator(BaseGenerator):
130 def __init__(self, bb_gen):
131 super(IsolatedScriptTestGenerator, self).__init__(bb_gen)
132
Kenneth Russell8ceeabf2017-12-11 17:53:28133 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28134 isolated_scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23135 for test_name, test_config in sorted(input_tests.items()):
Jeff Yoonb8bfdbf32020-03-13 19:14:43136 # Variants allow more than one definition for a given test, and is defined
137 # in array format from resolve_variants().
138 if not isinstance(test_config, list):
139 test_config = [test_config]
140
141 for config in test_config:
142 test = self.bb_gen.generate_isolated_script_test(
143 waterfall, tester_name, tester_config, test_name, config)
144 if test:
145 isolated_scripts.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28146 return isolated_scripts
147
Kenneth Russelleb60cbd22017-12-05 07:54:28148
149class ScriptGenerator(BaseGenerator):
150 def __init__(self, bb_gen):
151 super(ScriptGenerator, self).__init__(bb_gen)
152
Kenneth Russell8ceeabf2017-12-11 17:53:28153 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28154 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23155 for test_name, test_config in sorted(input_tests.items()):
Kenneth Russelleb60cbd22017-12-05 07:54:28156 test = self.bb_gen.generate_script_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28157 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28158 if test:
159 scripts.append(test)
160 return scripts
161
Kenneth Russelleb60cbd22017-12-05 07:54:28162
163class JUnitGenerator(BaseGenerator):
164 def __init__(self, bb_gen):
165 super(JUnitGenerator, self).__init__(bb_gen)
166
Kenneth Russell8ceeabf2017-12-11 17:53:28167 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28168 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23169 for test_name, test_config in sorted(input_tests.items()):
Kenneth Russelleb60cbd22017-12-05 07:54:28170 test = self.bb_gen.generate_junit_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28171 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28172 if test:
173 scripts.append(test)
174 return scripts
175
Kenneth Russelleb60cbd22017-12-05 07:54:28176
Xinan Lin05fb9c1752020-12-17 00:15:52177class SkylabGenerator(BaseGenerator):
178 def __init__(self, bb_gen):
179 super(SkylabGenerator, self).__init__(bb_gen)
180
181 def generate(self, waterfall, tester_name, tester_config, input_tests):
182 scripts = []
Jamie Madillcf4f8c72021-05-20 19:24:23183 for test_name, test_config in sorted(input_tests.items()):
Xinan Lin05fb9c1752020-12-17 00:15:52184 for config in test_config:
185 test = self.bb_gen.generate_skylab_test(waterfall, tester_name,
186 tester_config, test_name,
187 config)
188 if test:
189 scripts.append(test)
190 return scripts
191
Xinan Lin05fb9c1752020-12-17 00:15:52192
Jeff Yoon67c3e832020-02-08 07:39:38193def check_compound_references(other_test_suites=None,
194 sub_suite=None,
195 suite=None,
196 target_test_suites=None,
197 test_type=None,
198 **kwargs):
199 """Ensure comound reference's don't target other compounds"""
200 del kwargs
201 if sub_suite in other_test_suites or sub_suite in target_test_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15202 raise BBGenErr('%s may not refer to other composition type test '
203 'suites (error found while processing %s)' %
204 (test_type, suite))
205
Jeff Yoon67c3e832020-02-08 07:39:38206
207def check_basic_references(basic_suites=None,
208 sub_suite=None,
209 suite=None,
210 **kwargs):
211 """Ensure test has a basic suite reference"""
212 del kwargs
213 if sub_suite not in basic_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15214 raise BBGenErr('Unable to find reference to %s while processing %s' %
215 (sub_suite, suite))
216
Jeff Yoon67c3e832020-02-08 07:39:38217
218def check_conflicting_definitions(basic_suites=None,
219 seen_tests=None,
220 sub_suite=None,
221 suite=None,
222 test_type=None,
Garrett Beaty235c1412023-08-29 20:26:29223 target_test_suites=None,
Jeff Yoon67c3e832020-02-08 07:39:38224 **kwargs):
225 """Ensure that if a test is reachable via multiple basic suites,
226 all of them have an identical definition of the tests.
227 """
228 del kwargs
Garrett Beaty235c1412023-08-29 20:26:29229 variants = None
230 if test_type == 'matrix_compound_suites':
231 variants = target_test_suites[suite][sub_suite].get('variants')
232 variants = variants or [None]
Jeff Yoon67c3e832020-02-08 07:39:38233 for test_name in basic_suites[sub_suite]:
Garrett Beaty235c1412023-08-29 20:26:29234 for variant in variants:
235 key = (test_name, variant)
236 if ((seen_sub_suite := seen_tests.get(key)) is not None
237 and basic_suites[sub_suite][test_name] !=
238 basic_suites[seen_sub_suite][test_name]):
239 test_description = (test_name if variant is None else
240 f'{test_name} with variant {variant} applied')
241 raise BBGenErr(
242 'Conflicting test definitions for %s from %s '
243 'and %s in %s (error found while processing %s)' %
244 (test_description, seen_tests[key], sub_suite, test_type, suite))
245 seen_tests[key] = sub_suite
246
Jeff Yoon67c3e832020-02-08 07:39:38247
248def check_matrix_identifier(sub_suite=None,
249 suite=None,
250 suite_def=None,
Jeff Yoonda581c32020-03-06 03:56:05251 all_variants=None,
Jeff Yoon67c3e832020-02-08 07:39:38252 **kwargs):
253 """Ensure 'idenfitier' is defined for each variant"""
254 del kwargs
255 sub_suite_config = suite_def[sub_suite]
Garrett Beaty2022db42023-08-29 17:22:40256 for variant_name in sub_suite_config.get('variants', []):
257 if variant_name not in all_variants:
258 raise BBGenErr('Missing variant definition for %s in variants.pyl' %
259 variant_name)
260 variant = all_variants[variant_name]
Jeff Yoonda581c32020-03-06 03:56:05261
Jeff Yoon67c3e832020-02-08 07:39:38262 if not 'identifier' in variant:
263 raise BBGenErr('Missing required identifier field in matrix '
264 'compound suite %s, %s' % (suite, sub_suite))
Sven Zhengef0d0872022-04-04 22:13:29265 if variant['identifier'] == '':
266 raise BBGenErr('Identifier field can not be "" in matrix '
267 'compound suite %s, %s' % (suite, sub_suite))
268 if variant['identifier'].strip() != variant['identifier']:
269 raise BBGenErr('Identifier field can not have leading and trailing '
270 'whitespace in matrix compound suite %s, %s' %
271 (suite, sub_suite))
Jeff Yoon67c3e832020-02-08 07:39:38272
273
Joshua Hood56c673c2022-03-02 20:29:33274class BBJSONGenerator(object): # pylint: disable=useless-object-inheritance
Garrett Beaty1afaccc2020-06-25 19:58:15275 def __init__(self, args):
Garrett Beaty1afaccc2020-06-25 19:58:15276 self.args = args
Kenneth Russelleb60cbd22017-12-05 07:54:28277 self.waterfalls = None
278 self.test_suites = None
279 self.exceptions = None
Stephen Martinisb72f6d22018-10-04 23:29:01280 self.mixins = None
Nodir Turakulovfce34292019-12-18 17:05:41281 self.gn_isolate_map = None
Jeff Yoonda581c32020-03-06 03:56:05282 self.variants = None
Kenneth Russelleb60cbd22017-12-05 07:54:28283
Garrett Beaty1afaccc2020-06-25 19:58:15284 @staticmethod
285 def parse_args(argv):
286
287 # RawTextHelpFormatter allows for styling of help statement
288 parser = argparse.ArgumentParser(
289 formatter_class=argparse.RawTextHelpFormatter)
290
291 group = parser.add_mutually_exclusive_group()
292 group.add_argument(
293 '-c',
294 '--check',
295 action='store_true',
296 help=
297 'Do consistency checks of configuration and generated files and then '
298 'exit. Used during presubmit. '
299 'Causes the tool to not generate any files.')
300 group.add_argument(
301 '--query',
302 type=str,
303 help=(
304 "Returns raw JSON information of buildbots and tests.\n" +
305 "Examples:\n" + " List all bots (all info):\n" +
306 " --query bots\n\n" +
307 " List all bots and only their associated tests:\n" +
308 " --query bots/tests\n\n" +
309 " List all information about 'bot1' " +
310 "(make sure you have quotes):\n" + " --query bot/'bot1'\n\n" +
311 " List tests running for 'bot1' (make sure you have quotes):\n" +
312 " --query bot/'bot1'/tests\n\n" + " List all tests:\n" +
313 " --query tests\n\n" +
314 " List all tests and the bots running them:\n" +
315 " --query tests/bots\n\n" +
316 " List all tests that satisfy multiple parameters\n" +
317 " (separation of parameters by '&' symbol):\n" +
318 " --query tests/'device_os:Android&device_type:hammerhead'\n\n" +
319 " List all tests that run with a specific flag:\n" +
320 " --query bots/'--test-launcher-print-test-studio=always'\n\n" +
321 " List specific test (make sure you have quotes):\n"
322 " --query test/'test1'\n\n"
323 " List all bots running 'test1' " +
324 "(make sure you have quotes):\n" + " --query test/'test1'/bots"))
325 parser.add_argument(
Garrett Beaty79339e182023-04-10 20:45:47326 '--json',
327 metavar='JSON_FILE_PATH',
328 type=os.path.abspath,
329 help='Outputs results into a json file. Only works with query function.'
330 )
331 parser.add_argument(
Garrett Beaty1afaccc2020-06-25 19:58:15332 '-n',
333 '--new-files',
334 action='store_true',
335 help=
336 'Write output files as .new.json. Useful during development so old and '
337 'new files can be looked at side-by-side.')
Garrett Beatyade673d2023-08-04 22:00:25338 parser.add_argument('--dimension-sets-handling',
339 choices=['disable'],
340 default='disable',
341 help=('This flag no longer has any effect:'
342 ' dimension_sets fields are not allowed'))
Garrett Beaty1afaccc2020-06-25 19:58:15343 parser.add_argument('-v',
344 '--verbose',
345 action='store_true',
346 help='Increases verbosity. Affects consistency checks.')
347 parser.add_argument('waterfall_filters',
348 metavar='waterfalls',
349 type=str,
350 nargs='*',
351 help='Optional list of waterfalls to generate.')
352 parser.add_argument(
353 '--pyl-files-dir',
Garrett Beaty79339e182023-04-10 20:45:47354 type=os.path.abspath,
355 help=('Path to the directory containing the input .pyl files.'
356 ' By default the directory containing this script will be used.'))
Garrett Beaty1afaccc2020-06-25 19:58:15357 parser.add_argument(
Garrett Beaty79339e182023-04-10 20:45:47358 '--output-dir',
359 type=os.path.abspath,
360 help=('Path to the directory to output generated .json files.'
361 'By default, the pyl files directory will be used.'))
Chong Guee622242020-10-28 18:17:35362 parser.add_argument('--isolate-map-file',
363 metavar='PATH',
364 help='path to additional isolate map files.',
Garrett Beaty79339e182023-04-10 20:45:47365 type=os.path.abspath,
Chong Guee622242020-10-28 18:17:35366 default=[],
367 action='append',
368 dest='isolate_map_files')
Garrett Beaty1afaccc2020-06-25 19:58:15369 parser.add_argument(
370 '--infra-config-dir',
371 help='Path to the LUCI services configuration directory',
Garrett Beaty79339e182023-04-10 20:45:47372 type=os.path.abspath,
373 default=os.path.join(os.path.dirname(__file__), '..', '..', 'infra',
374 'config'))
375
Garrett Beaty1afaccc2020-06-25 19:58:15376 args = parser.parse_args(argv)
377 if args.json and not args.query:
378 parser.error(
379 "The --json flag can only be used with --query.") # pragma: no cover
Garrett Beaty1afaccc2020-06-25 19:58:15380
Garrett Beaty79339e182023-04-10 20:45:47381 args.pyl_files_dir = args.pyl_files_dir or THIS_DIR
382 args.output_dir = args.output_dir or args.pyl_files_dir
383
Stephanie Kim572b43c02023-04-13 14:24:13384 def absolute_file_path(filename):
Garrett Beaty79339e182023-04-10 20:45:47385 return os.path.join(args.pyl_files_dir, filename)
386
Stephanie Kim572b43c02023-04-13 14:24:13387 args.waterfalls_pyl_path = absolute_file_path('waterfalls.pyl')
Garrett Beaty96802d02023-07-07 14:18:05388 args.mixins_pyl_path = absolute_file_path('mixins.pyl')
Stephanie Kim572b43c02023-04-13 14:24:13389 args.test_suites_pyl_path = absolute_file_path('test_suites.pyl')
390 args.test_suite_exceptions_pyl_path = absolute_file_path(
Garrett Beaty79339e182023-04-10 20:45:47391 'test_suite_exceptions.pyl')
Stephanie Kim572b43c02023-04-13 14:24:13392 args.gn_isolate_map_pyl_path = absolute_file_path('gn_isolate_map.pyl')
393 args.variants_pyl_path = absolute_file_path('variants.pyl')
394 args.autoshard_exceptions_json_path = absolute_file_path(
395 'autoshard_exceptions.json')
Garrett Beaty79339e182023-04-10 20:45:47396
397 return args
Kenneth Russelleb60cbd22017-12-05 07:54:28398
Stephen Martinis7eb8b612018-09-21 00:17:50399 def print_line(self, line):
400 # Exists so that tests can mock
Jamie Madillcf4f8c72021-05-20 19:24:23401 print(line) # pragma: no cover
Stephen Martinis7eb8b612018-09-21 00:17:50402
Kenneth Russelleb60cbd22017-12-05 07:54:28403 def read_file(self, relative_path):
Garrett Beaty79339e182023-04-10 20:45:47404 with open(relative_path) as fp:
Garrett Beaty1afaccc2020-06-25 19:58:15405 return fp.read()
Kenneth Russelleb60cbd22017-12-05 07:54:28406
Garrett Beaty79339e182023-04-10 20:45:47407 def write_file(self, file_path, contents):
Peter Kastingacd55c12023-08-23 20:19:04408 with open(file_path, 'w', newline='') as fp:
Garrett Beaty79339e182023-04-10 20:45:47409 fp.write(contents)
Zhiling Huangbe008172018-03-08 19:13:11410
Joshua Hood56c673c2022-03-02 20:29:33411 # pylint: disable=inconsistent-return-statements
Garrett Beaty79339e182023-04-10 20:45:47412 def load_pyl_file(self, pyl_file_path):
Kenneth Russelleb60cbd22017-12-05 07:54:28413 try:
Garrett Beaty79339e182023-04-10 20:45:47414 return ast.literal_eval(self.read_file(pyl_file_path))
Kenneth Russelleb60cbd22017-12-05 07:54:28415 except (SyntaxError, ValueError) as e: # pragma: no cover
Josip Sokcevic7110fb382023-06-06 01:05:29416 raise BBGenErr('Failed to parse pyl file "%s": %s' %
417 (pyl_file_path, e)) from e
Joshua Hood56c673c2022-03-02 20:29:33418 # pylint: enable=inconsistent-return-statements
Kenneth Russelleb60cbd22017-12-05 07:54:28419
Kenneth Russell8a386d42018-06-02 09:48:01420 # TOOD(kbr): require that os_type be specified for all bots in waterfalls.pyl.
421 # Currently it is only mandatory for bots which run GPU tests. Change these to
422 # use [] instead of .get().
Kenneth Russelleb60cbd22017-12-05 07:54:28423 def is_android(self, tester_config):
424 return tester_config.get('os_type') == 'android'
425
Ben Pastenea9e583b2019-01-16 02:57:26426 def is_chromeos(self, tester_config):
427 return tester_config.get('os_type') == 'chromeos'
428
Chong Guc2ca5d02022-01-11 19:52:17429 def is_fuchsia(self, tester_config):
430 return tester_config.get('os_type') == 'fuchsia'
431
Brian Sheedy781c8ca42021-03-08 22:03:21432 def is_lacros(self, tester_config):
433 return tester_config.get('os_type') == 'lacros'
434
Kenneth Russell8a386d42018-06-02 09:48:01435 def is_linux(self, tester_config):
436 return tester_config.get('os_type') == 'linux'
437
Kai Ninomiya40de9f52019-10-18 21:38:49438 def is_mac(self, tester_config):
439 return tester_config.get('os_type') == 'mac'
440
441 def is_win(self, tester_config):
442 return tester_config.get('os_type') == 'win'
443
444 def is_win64(self, tester_config):
445 return (tester_config.get('os_type') == 'win' and
446 tester_config.get('browser_config') == 'release_x64')
447
Garrett Beatyffe83c4f2023-09-08 19:07:37448 def get_exception_for_test(self, test_config):
449 return self.exceptions.get(test_config['name'])
Kenneth Russelleb60cbd22017-12-05 07:54:28450
Garrett Beatyffe83c4f2023-09-08 19:07:37451 def should_run_on_tester(self, waterfall, tester_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28452 # Currently, the only reason a test should not run on a given tester is that
453 # it's in the exceptions. (Once the GPU waterfall generation script is
454 # incorporated here, the rules will become more complex.)
Garrett Beatyffe83c4f2023-09-08 19:07:37455 exception = self.get_exception_for_test(test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28456 if not exception:
457 return True
Kenneth Russell8ceeabf2017-12-11 17:53:28458 remove_from = None
Kenneth Russelleb60cbd22017-12-05 07:54:28459 remove_from = exception.get('remove_from')
Kenneth Russell8ceeabf2017-12-11 17:53:28460 if remove_from:
461 if tester_name in remove_from:
462 return False
463 # TODO(kbr): this code path was added for some tests (including
464 # android_webview_unittests) on one machine (Nougat Phone
465 # Tester) which exists with the same name on two waterfalls,
466 # chromium.android and chromium.fyi; the tests are run on one
467 # but not the other. Once the bots are all uniquely named (a
468 # different ongoing project) this code should be removed.
469 # TODO(kbr): add coverage.
470 return (tester_name + ' ' + waterfall['name']
471 not in remove_from) # pragma: no cover
472 return True
Kenneth Russelleb60cbd22017-12-05 07:54:28473
Garrett Beatyffe83c4f2023-09-08 19:07:37474 def get_test_modifications(self, test, tester_name):
475 exception = self.get_exception_for_test(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28476 if not exception:
477 return None
Nico Weber79dc5f6852018-07-13 19:38:49478 return exception.get('modifications', {}).get(tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28479
Garrett Beatyffe83c4f2023-09-08 19:07:37480 def get_test_replacements(self, test, tester_name):
481 exception = self.get_exception_for_test(test)
Brian Sheedye6ea0ee2019-07-11 02:54:37482 if not exception:
483 return None
484 return exception.get('replacements', {}).get(tester_name)
485
Kenneth Russell8a386d42018-06-02 09:48:01486 def merge_command_line_args(self, arr, prefix, splitter):
487 prefix_len = len(prefix)
Kenneth Russell650995a2018-05-03 21:17:01488 idx = 0
489 first_idx = -1
Kenneth Russell8a386d42018-06-02 09:48:01490 accumulated_args = []
Kenneth Russell650995a2018-05-03 21:17:01491 while idx < len(arr):
492 flag = arr[idx]
493 delete_current_entry = False
Kenneth Russell8a386d42018-06-02 09:48:01494 if flag.startswith(prefix):
495 arg = flag[prefix_len:]
496 accumulated_args.extend(arg.split(splitter))
Kenneth Russell650995a2018-05-03 21:17:01497 if first_idx < 0:
498 first_idx = idx
499 else:
500 delete_current_entry = True
501 if delete_current_entry:
502 del arr[idx]
503 else:
504 idx += 1
505 if first_idx >= 0:
Kenneth Russell8a386d42018-06-02 09:48:01506 arr[first_idx] = prefix + splitter.join(accumulated_args)
507 return arr
508
509 def maybe_fixup_args_array(self, arr):
510 # The incoming array of strings may be an array of command line
511 # arguments. To make it easier to turn on certain features per-bot or
512 # per-test-suite, look specifically for certain flags and merge them
513 # appropriately.
514 # --enable-features=Feature1 --enable-features=Feature2
515 # are merged to:
516 # --enable-features=Feature1,Feature2
517 # and:
518 # --extra-browser-args=arg1 --extra-browser-args=arg2
519 # are merged to:
520 # --extra-browser-args=arg1 arg2
521 arr = self.merge_command_line_args(arr, '--enable-features=', ',')
522 arr = self.merge_command_line_args(arr, '--extra-browser-args=', ' ')
Yuly Novikov8c487e72020-10-16 20:00:29523 arr = self.merge_command_line_args(arr, '--test-launcher-filter-file=', ';')
Cameron Higgins971f0b92023-01-03 18:05:09524 arr = self.merge_command_line_args(arr, '--extra-app-args=', ',')
Kenneth Russell650995a2018-05-03 21:17:01525 return arr
526
Brian Sheedy910cda82022-07-19 11:58:34527 def substitute_magic_args(self, test_config, tester_name, tester_config):
Brian Sheedya31578e2020-05-18 20:24:36528 """Substitutes any magic substitution args present in |test_config|.
529
530 Substitutions are done in-place.
531
532 See buildbot_json_magic_substitutions.py for more information on this
533 feature.
534
535 Args:
536 test_config: A dict containing a configuration for a specific test on
537 a specific builder, e.g. the output of update_and_cleanup_test.
Brian Sheedy5f173bb2021-11-24 00:45:54538 tester_name: A string containing the name of the tester that |test_config|
539 came from.
Brian Sheedy910cda82022-07-19 11:58:34540 tester_config: A dict containing the configuration for the builder that
541 |test_config| is for.
Brian Sheedya31578e2020-05-18 20:24:36542 """
543 substituted_array = []
Brian Sheedyba13cf522022-09-13 21:00:09544 original_args = test_config.get('args', [])
545 for arg in original_args:
Brian Sheedya31578e2020-05-18 20:24:36546 if arg.startswith(magic_substitutions.MAGIC_SUBSTITUTION_PREFIX):
547 function = arg.replace(
548 magic_substitutions.MAGIC_SUBSTITUTION_PREFIX, '')
549 if hasattr(magic_substitutions, function):
550 substituted_array.extend(
Brian Sheedy910cda82022-07-19 11:58:34551 getattr(magic_substitutions, function)(test_config, tester_name,
552 tester_config))
Brian Sheedya31578e2020-05-18 20:24:36553 else:
554 raise BBGenErr(
555 'Magic substitution function %s does not exist' % function)
556 else:
557 substituted_array.append(arg)
Brian Sheedyba13cf522022-09-13 21:00:09558 if substituted_array != original_args:
Brian Sheedya31578e2020-05-18 20:24:36559 test_config['args'] = self.maybe_fixup_args_array(substituted_array)
560
Garrett Beaty8d6708c2023-07-20 17:20:41561 def dictionary_merge(self, a, b, path=None):
Kenneth Russelleb60cbd22017-12-05 07:54:28562 """http://stackoverflow.com/questions/7204805/
563 python-dictionaries-of-dictionaries-merge
564 merges b into a
565 """
566 if path is None:
567 path = []
568 for key in b:
Garrett Beaty8d6708c2023-07-20 17:20:41569 if key not in a:
570 if b[key] is not None:
571 a[key] = b[key]
572 continue
573
574 if isinstance(a[key], dict) and isinstance(b[key], dict):
575 self.dictionary_merge(a[key], b[key], path + [str(key)])
576 elif a[key] == b[key]:
577 pass # same leaf value
578 elif isinstance(a[key], list) and isinstance(b[key], list):
Garrett Beatyade673d2023-08-04 22:00:25579 a[key] = a[key] + b[key]
580 if key.endswith('args'):
581 a[key] = self.maybe_fixup_args_array(a[key])
Garrett Beaty8d6708c2023-07-20 17:20:41582 elif b[key] is None:
583 del a[key]
584 else:
Kenneth Russelleb60cbd22017-12-05 07:54:28585 a[key] = b[key]
Garrett Beaty8d6708c2023-07-20 17:20:41586
Kenneth Russelleb60cbd22017-12-05 07:54:28587 return a
588
John Budorickab108712018-09-01 00:12:21589 def initialize_args_for_test(
590 self, generated_test, tester_config, additional_arg_keys=None):
John Budorickab108712018-09-01 00:12:21591 args = []
592 args.extend(generated_test.get('args', []))
593 args.extend(tester_config.get('args', []))
John Budorickedfe7f872018-01-23 15:27:22594
Kenneth Russell8a386d42018-06-02 09:48:01595 def add_conditional_args(key, fn):
John Budorickab108712018-09-01 00:12:21596 val = generated_test.pop(key, [])
597 if fn(tester_config):
598 args.extend(val)
Kenneth Russell8a386d42018-06-02 09:48:01599
600 add_conditional_args('desktop_args', lambda cfg: not self.is_android(cfg))
Brian Sheedy781c8ca42021-03-08 22:03:21601 add_conditional_args('lacros_args', self.is_lacros)
Kenneth Russell8a386d42018-06-02 09:48:01602 add_conditional_args('linux_args', self.is_linux)
603 add_conditional_args('android_args', self.is_android)
Ben Pastene52890ace2019-05-24 20:03:36604 add_conditional_args('chromeos_args', self.is_chromeos)
Kai Ninomiya40de9f52019-10-18 21:38:49605 add_conditional_args('mac_args', self.is_mac)
606 add_conditional_args('win_args', self.is_win)
607 add_conditional_args('win64_args', self.is_win64)
Kenneth Russell8a386d42018-06-02 09:48:01608
John Budorickab108712018-09-01 00:12:21609 for key in additional_arg_keys or []:
610 args.extend(generated_test.pop(key, []))
611 args.extend(tester_config.get(key, []))
612
613 if args:
614 generated_test['args'] = self.maybe_fixup_args_array(args)
Kenneth Russell8a386d42018-06-02 09:48:01615
Kenneth Russelleb60cbd22017-12-05 07:54:28616 def initialize_swarming_dictionary_for_test(self, generated_test,
617 tester_config):
618 if 'swarming' not in generated_test:
619 generated_test['swarming'] = {}
Dirk Pranke81ff51c2017-12-09 19:24:28620 if not 'can_use_on_swarming_builders' in generated_test['swarming']:
621 generated_test['swarming'].update({
Jeff Yoon67c3e832020-02-08 07:39:38622 'can_use_on_swarming_builders': tester_config.get('use_swarming',
623 True)
Dirk Pranke81ff51c2017-12-09 19:24:28624 })
Kenneth Russelleb60cbd22017-12-05 07:54:28625 if 'swarming' in tester_config:
Kenneth Russelleb60cbd22017-12-05 07:54:28626 self.dictionary_merge(generated_test['swarming'],
627 tester_config['swarming'])
Brian Sheedybc984e242021-04-21 23:44:51628 # Apply any platform-specific Swarming dimensions after the generic ones.
Kenneth Russelleb60cbd22017-12-05 07:54:28629 if 'android_swarming' in generated_test:
630 if self.is_android(tester_config): # pragma: no cover
631 self.dictionary_merge(
632 generated_test['swarming'],
633 generated_test['android_swarming']) # pragma: no cover
634 del generated_test['android_swarming'] # pragma: no cover
Brian Sheedybc984e242021-04-21 23:44:51635 if 'chromeos_swarming' in generated_test:
636 if self.is_chromeos(tester_config): # pragma: no cover
637 self.dictionary_merge(
638 generated_test['swarming'],
639 generated_test['chromeos_swarming']) # pragma: no cover
640 del generated_test['chromeos_swarming'] # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:28641
642 def clean_swarming_dictionary(self, swarming_dict):
643 # Clean out redundant entries from a test's "swarming" dictionary.
644 # This is really only needed to retain 100% parity with the
645 # handwritten JSON files, and can be removed once all the files are
646 # autogenerated.
647 if 'shards' in swarming_dict:
648 if swarming_dict['shards'] == 1: # pragma: no cover
649 del swarming_dict['shards'] # pragma: no cover
Kenneth Russellfbda3c532017-12-08 23:57:24650 if 'hard_timeout' in swarming_dict:
651 if swarming_dict['hard_timeout'] == 0: # pragma: no cover
652 del swarming_dict['hard_timeout'] # pragma: no cover
Garrett Beatybb18d532023-06-26 22:16:33653 del swarming_dict['can_use_on_swarming_builders']
Kenneth Russelleb60cbd22017-12-05 07:54:28654
Stephen Martinis0382bc12018-09-17 22:29:07655 def update_and_cleanup_test(self, test, test_name, tester_name, tester_config,
656 waterfall):
657 # Apply swarming mixins.
Stephen Martinisb72f6d22018-10-04 23:29:01658 test = self.apply_all_mixins(
Stephen Martinis0382bc12018-09-17 22:29:07659 test, waterfall, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28660 # See if there are any exceptions that need to be merged into this
661 # test's specification.
Garrett Beatyffe83c4f2023-09-08 19:07:37662 modifications = self.get_test_modifications(test, tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28663 if modifications:
664 test = self.dictionary_merge(test, modifications)
Garrett Beatybfeff8f2023-06-16 18:57:25665 if (swarming_dict := test.get('swarming')) is not None:
Garrett Beatybb18d532023-06-26 22:16:33666 if swarming_dict.get('can_use_on_swarming_builders'):
Garrett Beatybfeff8f2023-06-16 18:57:25667 self.clean_swarming_dictionary(swarming_dict)
668 else:
669 del test['swarming']
Ben Pastenee012aea42019-05-14 22:32:28670 # Ensure all Android Swarming tests run only on userdebug builds if another
671 # build type was not specified.
672 if 'swarming' in test and self.is_android(tester_config):
Garrett Beatyade673d2023-08-04 22:00:25673 dimensions = test.get('swarming', {}).get('dimensions', {})
674 if (dimensions.get('os') == 'Android'
675 and not dimensions.get('device_os_type')):
676 dimensions['device_os_type'] = 'userdebug'
Brian Sheedye6ea0ee2019-07-11 02:54:37677 self.replace_test_args(test, test_name, tester_name)
Garrett Beatyafd33e0f2023-06-23 20:47:57678 if 'args' in test and not test['args']:
679 test.pop('args')
Ben Pastenee012aea42019-05-14 22:32:28680
Kenneth Russelleb60cbd22017-12-05 07:54:28681 return test
682
Brian Sheedye6ea0ee2019-07-11 02:54:37683 def replace_test_args(self, test, test_name, tester_name):
Garrett Beatyffe83c4f2023-09-08 19:07:37684 replacements = self.get_test_replacements(test, tester_name) or {}
Brian Sheedye6ea0ee2019-07-11 02:54:37685 valid_replacement_keys = ['args', 'non_precommit_args', 'precommit_args']
Jamie Madillcf4f8c72021-05-20 19:24:23686 for key, replacement_dict in replacements.items():
Brian Sheedye6ea0ee2019-07-11 02:54:37687 if key not in valid_replacement_keys:
688 raise BBGenErr(
689 'Given replacement key %s for %s on %s is not in the list of valid '
690 'keys %s' % (key, test_name, tester_name, valid_replacement_keys))
Jamie Madillcf4f8c72021-05-20 19:24:23691 for replacement_key, replacement_val in replacement_dict.items():
Brian Sheedye6ea0ee2019-07-11 02:54:37692 found_key = False
693 for i, test_key in enumerate(test.get(key, [])):
694 # Handle both the key/value being replaced being defined as two
695 # separate items or as key=value.
696 if test_key == replacement_key:
697 found_key = True
698 # Handle flags without values.
699 if replacement_val == None:
700 del test[key][i]
701 else:
702 test[key][i+1] = replacement_val
703 break
Joshua Hood56c673c2022-03-02 20:29:33704 if test_key.startswith(replacement_key + '='):
Brian Sheedye6ea0ee2019-07-11 02:54:37705 found_key = True
706 if replacement_val == None:
707 del test[key][i]
708 else:
709 test[key][i] = '%s=%s' % (replacement_key, replacement_val)
710 break
711 if not found_key:
712 raise BBGenErr('Could not find %s in existing list of values for key '
713 '%s in %s on %s' % (replacement_key, key, test_name,
714 tester_name))
715
Shenghua Zhangaba8bad2018-02-07 02:12:09716 def add_common_test_properties(self, test, tester_config):
Brian Sheedy5ea8f6c62020-05-21 03:05:05717 if self.is_chromeos(tester_config) and tester_config.get('use_swarming',
Ben Pastenea9e583b2019-01-16 02:57:26718 True):
719 # The presence of the "device_type" dimension indicates that the tests
Brian Sheedy9493da892020-05-13 22:58:06720 # are targeting CrOS hardware and so need the special trigger script.
Garrett Beatyade673d2023-08-04 22:00:25721 if 'device_type' in test.get('swarming', {}).get('dimensions', {}):
Ben Pastenea9e583b2019-01-16 02:57:26722 test['trigger_script'] = {
723 'script': '//testing/trigger_scripts/chromeos_device_trigger.py',
724 }
Shenghua Zhangaba8bad2018-02-07 02:12:09725
Garrett Beatyffe83c4f2023-09-08 19:07:37726 def add_android_presentation_args(self, tester_config, result):
Ben Pastene858f4be2019-01-09 23:52:09727 args = result.get('args', [])
John Budorick262ae112019-07-12 19:24:38728 bucket = tester_config.get('results_bucket', 'chromium-result-details')
729 args.append('--gs-results-bucket=%s' % bucket)
Ben Pastene858f4be2019-01-09 23:52:09730 if (result['swarming']['can_use_on_swarming_builders'] and not
731 tester_config.get('skip_merge_script', False)):
732 result['merge'] = {
Garrett Beatyffe83c4f2023-09-08 19:07:37733 'args': [
734 '--bucket',
735 bucket,
736 '--test-name',
737 result['name'],
738 ],
739 'script': ('//build/android/pylib/results/presentation/'
740 'test_results_presentation.py'),
Ben Pastene858f4be2019-01-09 23:52:09741 }
Ben Pastene858f4be2019-01-09 23:52:09742 if not tester_config.get('skip_output_links', False):
743 result['swarming']['output_links'] = [
744 {
745 'link': [
746 'https://luci-logdog.appspot.com/v/?s',
747 '=android%2Fswarming%2Flogcats%2F',
748 '${TASK_ID}%2F%2B%2Funified_logcats',
749 ],
750 'name': 'shard #${SHARD_INDEX} logcats',
751 },
752 ]
753 if args:
754 result['args'] = args
755
Kenneth Russelleb60cbd22017-12-05 07:54:28756 def generate_gtest(self, waterfall, tester_name, tester_config, test_name,
757 test_config):
Garrett Beatyffe83c4f2023-09-08 19:07:37758 if not self.should_run_on_tester(waterfall, tester_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28759 return None
760 result = copy.deepcopy(test_config)
Garrett Beatyffe83c4f2023-09-08 19:07:37761 # Use test_name here instead of test['name'] because test['name'] will be
762 # modified with the variant identifier in a matrix compound suite
763 result.setdefault('test', test_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28764 self.initialize_swarming_dictionary_for_test(result, tester_config)
John Budorickab108712018-09-01 00:12:21765
766 self.initialize_args_for_test(
767 result, tester_config, additional_arg_keys=['gtest_args'])
Jamie Madilla8be0d72020-10-02 05:24:04768 if self.is_android(tester_config) and tester_config.get(
Yuly Novikov26dd47052021-02-11 00:57:14769 'use_swarming', True):
770 if not test_config.get('use_isolated_scripts_api', False):
771 # TODO(https://crbug.com/1137998) make Android presentation work with
772 # isolated scripts in test_results_presentation.py merge script
Garrett Beatyffe83c4f2023-09-08 19:07:37773 self.add_android_presentation_args(tester_config, result)
Yuly Novikov26dd47052021-02-11 00:57:14774 result['args'] = result.get('args', []) + ['--recover-devices']
Benjamin Pastene766d48f52017-12-18 21:47:42775
Stephen Martinis0382bc12018-09-17 22:29:07776 result = self.update_and_cleanup_test(
777 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09778 self.add_common_test_properties(result, tester_config)
Brian Sheedy910cda82022-07-19 11:58:34779 self.substitute_magic_args(result, tester_name, tester_config)
Stephen Martinisbc7b7772019-05-01 22:01:43780
Garrett Beatybb18d532023-06-26 22:16:33781 if 'swarming' in result and not result.get('merge'):
Jamie Madilla8be0d72020-10-02 05:24:04782 if test_config.get('use_isolated_scripts_api', False):
783 merge_script = 'standard_isolated_script_merge'
784 else:
785 merge_script = 'standard_gtest_merge'
786
Stephen Martinisbc7b7772019-05-01 22:01:43787 result['merge'] = {
Jamie Madilla8be0d72020-10-02 05:24:04788 'script': '//testing/merge_scripts/%s.py' % merge_script,
Stephen Martinisbc7b7772019-05-01 22:01:43789 }
Kenneth Russelleb60cbd22017-12-05 07:54:28790 return result
791
792 def generate_isolated_script_test(self, waterfall, tester_name, tester_config,
793 test_name, test_config):
Garrett Beatyffe83c4f2023-09-08 19:07:37794 if not self.should_run_on_tester(waterfall, tester_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28795 return None
796 result = copy.deepcopy(test_config)
Garrett Beatyffe83c4f2023-09-08 19:07:37797 # Use test_name here instead of test['name'] because test['name'] will be
798 # modified with the variant identifier in a matrix compound suite
Garrett Beatydca3d882023-09-14 23:50:32799 result.setdefault('test', test_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28800 self.initialize_swarming_dictionary_for_test(result, tester_config)
Kenneth Russell8a386d42018-06-02 09:48:01801 self.initialize_args_for_test(result, tester_config)
Yuly Novikov26dd47052021-02-11 00:57:14802 if self.is_android(tester_config) and tester_config.get(
803 'use_swarming', True):
804 if tester_config.get('use_android_presentation', False):
805 # TODO(https://crbug.com/1137998) make Android presentation work with
806 # isolated scripts in test_results_presentation.py merge script
Garrett Beatyffe83c4f2023-09-08 19:07:37807 self.add_android_presentation_args(tester_config, result)
Stephen Martinis0382bc12018-09-17 22:29:07808 result = self.update_and_cleanup_test(
809 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09810 self.add_common_test_properties(result, tester_config)
Brian Sheedy910cda82022-07-19 11:58:34811 self.substitute_magic_args(result, tester_name, tester_config)
Stephen Martinisf50047062019-05-06 22:26:17812
Garrett Beatybb18d532023-06-26 22:16:33813 if 'swarming' in result and not result.get('merge'):
Stephen Martinisf50047062019-05-06 22:26:17814 # TODO(https://crbug.com/958376): Consider adding the ability to not have
815 # this default.
816 result['merge'] = {
817 'script': '//testing/merge_scripts/standard_isolated_script_merge.py',
Stephen Martinisf50047062019-05-06 22:26:17818 }
Kenneth Russelleb60cbd22017-12-05 07:54:28819 return result
820
821 def generate_script_test(self, waterfall, tester_name, tester_config,
822 test_name, test_config):
Brian Sheedy158cd0f2019-04-26 01:12:44823 # TODO(https://crbug.com/953072): Remove this check whenever a better
824 # long-term solution is implemented.
825 if (waterfall.get('forbid_script_tests', False) or
826 waterfall['machines'][tester_name].get('forbid_script_tests', False)):
827 raise BBGenErr('Attempted to generate a script test on tester ' +
828 tester_name + ', which explicitly forbids script tests')
Garrett Beatyffe83c4f2023-09-08 19:07:37829 if not self.should_run_on_tester(waterfall, tester_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28830 return None
831 result = {
Garrett Beatyffe83c4f2023-09-08 19:07:37832 'name': test_config['name'],
833 'script': test_config['script'],
Kenneth Russelleb60cbd22017-12-05 07:54:28834 }
Stephen Martinis0382bc12018-09-17 22:29:07835 result = self.update_and_cleanup_test(
836 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedy910cda82022-07-19 11:58:34837 self.substitute_magic_args(result, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28838 return result
839
840 def generate_junit_test(self, waterfall, tester_name, tester_config,
841 test_name, test_config):
Garrett Beatyffe83c4f2023-09-08 19:07:37842 if not self.should_run_on_tester(waterfall, tester_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28843 return None
John Budorickdef6acb2019-09-17 22:51:09844 result = copy.deepcopy(test_config)
Garrett Beatyffe83c4f2023-09-08 19:07:37845 # Use test_name here instead of test['name'] because test['name'] will be
846 # modified with the variant identifier in a matrix compound suite
847 result.setdefault('test', test_name)
John Budorickdef6acb2019-09-17 22:51:09848 self.initialize_args_for_test(result, tester_config)
849 result = self.update_and_cleanup_test(
850 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedy910cda82022-07-19 11:58:34851 self.substitute_magic_args(result, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28852 return result
853
Xinan Lin05fb9c1752020-12-17 00:15:52854 def generate_skylab_test(self, waterfall, tester_name, tester_config,
855 test_name, test_config):
Garrett Beatyffe83c4f2023-09-08 19:07:37856 if not self.should_run_on_tester(waterfall, tester_name, test_config):
Xinan Lin05fb9c1752020-12-17 00:15:52857 return None
858 result = copy.deepcopy(test_config)
Brian Sheedy67937ad12024-03-06 22:53:55859 result.setdefault('test', test_name)
Xinan Lin05fb9c1752020-12-17 00:15:52860 self.initialize_args_for_test(result, tester_config)
861 result = self.update_and_cleanup_test(result, test_name, tester_name,
862 tester_config, waterfall)
Brian Sheedy910cda82022-07-19 11:58:34863 self.substitute_magic_args(result, tester_name, tester_config)
Xinan Lin05fb9c1752020-12-17 00:15:52864 return result
865
Garrett Beaty65d44222023-08-01 17:22:11866 def substitute_gpu_args(self, tester_config, test, args):
Kenneth Russell8a386d42018-06-02 09:48:01867 substitutions = {
868 # Any machine in waterfalls.pyl which desires to run GPU tests
869 # must provide the os_type key.
870 'os_type': tester_config['os_type'],
871 'gpu_vendor_id': '0',
872 'gpu_device_id': '0',
873 }
Garrett Beatyade673d2023-08-04 22:00:25874 dimensions = test.get('swarming', {}).get('dimensions', {})
875 if 'gpu' in dimensions:
876 # First remove the driver version, then split into vendor and device.
877 gpu = dimensions['gpu']
878 if gpu != 'none':
879 gpu = gpu.split('-')[0].split(':')
880 substitutions['gpu_vendor_id'] = gpu[0]
881 substitutions['gpu_device_id'] = gpu[1]
Kenneth Russell8a386d42018-06-02 09:48:01882 return [string.Template(arg).safe_substitute(substitutions) for arg in args]
883
884 def generate_gpu_telemetry_test(self, waterfall, tester_name, tester_config,
Fabrice de Ganscbd655f2022-08-04 20:15:30885 test_name, test_config, is_android_webview,
Xinan Linedcf05b32023-10-19 23:13:50886 is_cast_streaming, is_skylab):
Kenneth Russell8a386d42018-06-02 09:48:01887 # These are all just specializations of isolated script tests with
888 # a bunch of boilerplate command line arguments added.
889
890 # The step name must end in 'test' or 'tests' in order for the
891 # results to automatically show up on the flakiness dashboard.
892 # (At least, this was true some time ago.) Continue to use this
893 # naming convention for the time being to minimize changes.
Garrett Beaty235c1412023-08-29 20:26:29894 #
895 # test name is the name of the test without the variant ID added
896 if not (test_name.endswith('test') or test_name.endswith('tests')):
897 raise BBGenErr(
898 f'telemetry test names must end with test or tests, got {test_name}')
Garrett Beatyffe83c4f2023-09-08 19:07:37899 result = self.generate_isolated_script_test(waterfall, tester_name,
900 tester_config, test_name,
901 test_config)
Kenneth Russell8a386d42018-06-02 09:48:01902 if not result:
903 return None
Garrett Beatydca3d882023-09-14 23:50:32904 result['test'] = test_config.get('test') or self.get_default_isolate_name(
905 tester_config, is_android_webview)
Chan Liab7d8dd82020-04-24 23:42:19906
Chan Lia3ad1502020-04-28 05:32:11907 # Populate test_id_prefix.
Garrett Beatydca3d882023-09-14 23:50:32908 gn_entry = self.gn_isolate_map[result['test']]
Chan Li17d969f92020-07-10 00:50:03909 result['test_id_prefix'] = 'ninja:%s/' % gn_entry['label']
Chan Liab7d8dd82020-04-24 23:42:19910
Kenneth Russell8a386d42018-06-02 09:48:01911 args = result.get('args', [])
Garrett Beatyffe83c4f2023-09-08 19:07:37912 # Use test_name here instead of test['name'] because test['name'] will be
913 # modified with the variant identifier in a matrix compound suite
Kenneth Russell8a386d42018-06-02 09:48:01914 test_to_run = result.pop('telemetry_test_name', test_name)
erikchen6da2d9b2018-08-03 23:01:14915
erikchen6da2d9b2018-08-03 23:01:14916 # These tests upload and download results from cloud storage and therefore
917 # aren't idempotent yet. https://crbug.com/549140.
Garrett Beatybfeff8f2023-06-16 18:57:25918 if 'swarming' in result:
919 result['swarming']['idempotent'] = False
erikchen6da2d9b2018-08-03 23:01:14920
Fabrice de Ganscbd655f2022-08-04 20:15:30921 browser = ''
922 if is_cast_streaming:
923 browser = 'cast-streaming-shell'
924 elif is_android_webview:
925 browser = 'android-webview-instrumentation'
926 else:
927 browser = tester_config['browser_config']
Brian Sheedy4053a702020-07-28 02:09:52928
Greg Thompsoncec7d8d2023-01-10 19:11:53929 extra_browser_args = []
930
Brian Sheedy4053a702020-07-28 02:09:52931 # Most platforms require --enable-logging=stderr to get useful browser logs.
932 # However, this actively messes with logging on CrOS (because Chrome's
933 # stderr goes nowhere on CrOS) AND --log-level=0 is required for some reason
934 # in order to see JavaScript console messages. See
935 # https://chromium.googlesource.com/chromium/src.git/+/HEAD/docs/chrome_os_logging.md
Greg Thompsoncec7d8d2023-01-10 19:11:53936 if self.is_chromeos(tester_config):
937 extra_browser_args.append('--log-level=0')
938 elif not self.is_fuchsia(tester_config) or browser != 'fuchsia-chrome':
939 # Stderr logging is not needed for Chrome browser on Fuchsia, as ordinary
940 # logging via syslog is captured.
941 extra_browser_args.append('--enable-logging=stderr')
942
943 # --expose-gc allows the WebGL conformance tests to more reliably
944 # reproduce GC-related bugs in the V8 bindings.
945 extra_browser_args.append('--js-flags=--expose-gc')
Brian Sheedy4053a702020-07-28 02:09:52946
Xinan Linedcf05b32023-10-19 23:13:50947 # Skylab supports sharding, so reuse swarming's shard config.
948 if is_skylab and 'shards' not in result and test_config.get(
949 'swarming', {}).get('shards'):
950 result['shards'] = test_config['swarming']['shards']
951
Kenneth Russell8a386d42018-06-02 09:48:01952 args = [
Bo Liu555a0f92019-03-29 12:11:56953 test_to_run,
954 '--show-stdout',
955 '--browser=%s' % browser,
956 # --passthrough displays more of the logging in Telemetry when
957 # run via typ, in particular some of the warnings about tests
958 # being expected to fail, but passing.
959 '--passthrough',
960 '-v',
Brian Sheedy814e0482022-10-03 23:24:12961 '--stable-jobs',
Greg Thompsoncec7d8d2023-01-10 19:11:53962 '--extra-browser-args=%s' % ' '.join(extra_browser_args),
Brian Sheedy997e4802023-10-18 02:28:13963 '--enforce-browser-version',
Kenneth Russell8a386d42018-06-02 09:48:01964 ] + args
Garrett Beatybfeff8f2023-06-16 18:57:25965 result['args'] = self.maybe_fixup_args_array(
Garrett Beaty65d44222023-08-01 17:22:11966 self.substitute_gpu_args(tester_config, result, args))
Kenneth Russell8a386d42018-06-02 09:48:01967 return result
968
Brian Sheedyf74819b2021-06-04 01:38:38969 def get_default_isolate_name(self, tester_config, is_android_webview):
970 if self.is_android(tester_config):
971 if is_android_webview:
972 return 'telemetry_gpu_integration_test_android_webview'
973 return (
974 'telemetry_gpu_integration_test' +
975 BROWSER_CONFIG_TO_TARGET_SUFFIX_MAP[tester_config['browser_config']])
Joshua Hood56c673c2022-03-02 20:29:33976 if self.is_fuchsia(tester_config):
Chong Guc2ca5d02022-01-11 19:52:17977 return 'telemetry_gpu_integration_test_fuchsia'
Joshua Hood56c673c2022-03-02 20:29:33978 return 'telemetry_gpu_integration_test'
Brian Sheedyf74819b2021-06-04 01:38:38979
Kenneth Russelleb60cbd22017-12-05 07:54:28980 def get_test_generator_map(self):
981 return {
Bo Liu555a0f92019-03-29 12:11:56982 'android_webview_gpu_telemetry_tests':
Fabrice de Ganscbd655f2022-08-04 20:15:30983 GPUTelemetryTestGenerator(self, is_android_webview=True),
984 'cast_streaming_tests':
985 GPUTelemetryTestGenerator(self, is_cast_streaming=True),
Bo Liu555a0f92019-03-29 12:11:56986 'gpu_telemetry_tests':
Fabrice de Ganscbd655f2022-08-04 20:15:30987 GPUTelemetryTestGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56988 'gtest_tests':
Fabrice de Ganscbd655f2022-08-04 20:15:30989 GTestGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56990 'isolated_scripts':
Fabrice de Ganscbd655f2022-08-04 20:15:30991 IsolatedScriptTestGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56992 'junit_tests':
Fabrice de Ganscbd655f2022-08-04 20:15:30993 JUnitGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56994 'scripts':
Fabrice de Ganscbd655f2022-08-04 20:15:30995 ScriptGenerator(self),
Xinan Lin05fb9c1752020-12-17 00:15:52996 'skylab_tests':
Fabrice de Ganscbd655f2022-08-04 20:15:30997 SkylabGenerator(self),
Brian Sheedyb6491ba2022-09-26 20:49:49998 'skylab_gpu_telemetry_tests':
999 SkylabGPUTelemetryTestGenerator(self),
Kenneth Russelleb60cbd22017-12-05 07:54:281000 }
1001
Kenneth Russell8a386d42018-06-02 09:48:011002 def get_test_type_remapper(self):
1003 return {
Fabrice de Gans223272482022-08-08 16:56:571004 # These are a specialization of isolated_scripts with a bunch of
1005 # boilerplate command line arguments added to each one.
1006 'android_webview_gpu_telemetry_tests': 'isolated_scripts',
1007 'cast_streaming_tests': 'isolated_scripts',
1008 'gpu_telemetry_tests': 'isolated_scripts',
Brian Sheedyb6491ba2022-09-26 20:49:491009 # These are the same as existing test types, just configured to run
1010 # in Skylab instead of via normal swarming.
1011 'skylab_gpu_telemetry_tests': 'skylab_tests',
Kenneth Russell8a386d42018-06-02 09:48:011012 }
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
Garrett Beatydca3d882023-09-14 23:50:321064 isolate_name = test.get('test') or key
Nodir Turakulovfce34292019-12-18 17:05:411065 gn_entry = self.gn_isolate_map.get(isolate_name)
1066 if gn_entry:
Corentin Wallez55b8e772020-04-24 17:39:281067 label = gn_entry['label']
1068
1069 if label.count(':') != 1:
1070 raise BBGenErr(
1071 'Malformed GN label "%s" in gn_isolate_map for key "%s",'
1072 ' implicit names (like //f/b meaning //f/b:b) are disallowed.' %
1073 (label, isolate_name))
1074 if label.split(':')[1] != isolate_name:
1075 raise BBGenErr(
1076 'gn_isolate_map key name "%s" doesn\'t match GN target name in'
1077 ' label "%s" see http://crbug.com/1071091 for details.' %
1078 (isolate_name, label))
1079
Chan Lia3ad1502020-04-28 05:32:111080 test['test_id_prefix'] = 'ninja:%s/' % label
Nodir Turakulovfce34292019-12-18 17:05:411081 else: # pragma: no cover
1082 # Some tests do not have an entry gn_isolate_map.pyl, such as
1083 # telemetry tests.
1084 # TODO(crbug.com/1035304): require an entry in gn_isolate_map.
1085 pass
1086
Kenneth Russelleb60cbd22017-12-05 07:54:281087 def resolve_composition_test_suites(self):
Jeff Yoon8154e582019-12-03 23:30:011088 self.check_composition_type_test_suites('compound_suites')
Stephen Martinis54d64ad2018-09-21 22:16:201089
Jeff Yoon8154e582019-12-03 23:30:011090 compound_suites = self.test_suites.get('compound_suites', {})
1091 # check_composition_type_test_suites() checks that all basic suites
1092 # referenced by compound suites exist.
1093 basic_suites = self.test_suites.get('basic_suites')
1094
Jamie Madillcf4f8c72021-05-20 19:24:231095 for name, value in compound_suites.items():
Jeff Yoon8154e582019-12-03 23:30:011096 # Resolve this to a dictionary.
1097 full_suite = {}
1098 for entry in value:
1099 suite = basic_suites[entry]
1100 full_suite.update(suite)
1101 compound_suites[name] = full_suite
1102
Jeff Yoon85fb8df2020-08-20 16:47:431103 def resolve_variants(self, basic_test_definition, variants, mixins):
Jeff Yoon67c3e832020-02-08 07:39:381104 """ Merge variant-defined configurations to each test case definition in a
1105 test suite.
1106
1107 The output maps a unique test name to an array of configurations because
1108 there may exist more than one definition for a test name using variants. The
1109 test name is referenced while mapping machines to test suites, so unpacking
1110 the array is done by the generators.
1111
1112 Args:
1113 basic_test_definition: a {} defined test suite in the format
1114 test_name:test_config
1115 variants: an [] of {} defining configurations to be applied to each test
1116 case in the basic test_definition
1117
1118 Return:
1119 a {} of test_name:[{}], where each {} is a merged configuration
1120 """
1121
1122 # Each test in a basic test suite will have a definition per variant.
1123 test_suite = {}
Garrett Beaty8d6708c2023-07-20 17:20:411124 for variant in variants:
1125 # Unpack the variant from variants.pyl if it's string based.
1126 if isinstance(variant, str):
1127 variant = self.variants[variant]
Jeff Yoonda581c32020-03-06 03:56:051128
Garrett Beaty8d6708c2023-07-20 17:20:411129 # If 'enabled' is set to False, we will not use this variant; otherwise if
1130 # the variant doesn't include 'enabled' variable or 'enabled' is set to
1131 # True, we will use this variant
1132 if not variant.get('enabled', True):
1133 continue
Jeff Yoon67c3e832020-02-08 07:39:381134
Garrett Beaty8d6708c2023-07-20 17:20:411135 # Make a shallow copy of the variant to remove variant-specific fields,
1136 # leaving just mixin fields
1137 variant = copy.copy(variant)
1138 variant.pop('enabled', None)
1139 identifier = variant.pop('identifier')
1140 variant_mixins = variant.pop('mixins', [])
1141 variant_skylab = variant.pop('skylab', {})
Jeff Yoon67c3e832020-02-08 07:39:381142
Garrett Beaty8d6708c2023-07-20 17:20:411143 for test_name, test_config in basic_test_definition.items():
1144 new_test = self.apply_mixin(variant, test_config)
Jeff Yoon67c3e832020-02-08 07:39:381145
Garrett Beaty8d6708c2023-07-20 17:20:411146 new_test['mixins'] = (test_config.get('mixins', []) + variant_mixins +
1147 mixins)
Xinan Lin05fb9c1752020-12-17 00:15:521148
Jeff Yoon67c3e832020-02-08 07:39:381149 # The identifier is used to make the name of the test unique.
1150 # Generators in the recipe uniquely identify a test by it's name, so we
1151 # don't want to have the same name for each variant.
Garrett Beaty235c1412023-08-29 20:26:291152 new_test['name'] = f'{test_name} {identifier}'
Ben Pastene5f231cf22022-05-05 18:03:071153
1154 # Attach the variant identifier to the test config so downstream
1155 # generators can make modifications based on the original name. This
1156 # is mainly used in generate_gpu_telemetry_test().
Garrett Beaty8d6708c2023-07-20 17:20:411157 new_test['variant_id'] = identifier
Ben Pastene5f231cf22022-05-05 18:03:071158
Garrett Beaty8d6708c2023-07-20 17:20:411159 for k, v in variant_skylab.items():
Sven Zheng22ba6312023-10-16 22:59:351160 # cros_chrome_version is the ash chrome version in the cros img in the
1161 # variant of cros_board. We don't want to include it in the final json
1162 # files; so remove it.
Garrett Beaty8d6708c2023-07-20 17:20:411163 if k != 'cros_chrome_version':
1164 new_test[k] = v
1165
Sven Zheng22ba6312023-10-16 22:59:351166 # For skylab, we need to pop the correct `autotest_name`. This field
1167 # defines what wrapper we use in OS infra. e.g. for gtest it's
1168 # https://source.chromium.org/chromiumos/chromiumos/codesearch/+/main:src/third_party/autotest/files/server/site_tests/chromium/chromium.py
1169 if variant_skylab and 'autotest_name' not in new_test:
1170 if 'tast_expr' in test_config:
1171 if 'lacros' in test_config['name']:
1172 new_test['autotest_name'] = 'tast.lacros-from-gcs'
1173 else:
1174 new_test['autotest_name'] = 'tast.chrome-from-gcs'
1175 elif 'benchmark' in test_config:
1176 new_test['autotest_name'] = 'chromium_Telemetry'
1177 else:
1178 new_test['autotest_name'] = 'chromium'
1179
Garrett Beaty8d6708c2023-07-20 17:20:411180 test_suite.setdefault(test_name, []).append(new_test)
1181
Jeff Yoon67c3e832020-02-08 07:39:381182 return test_suite
1183
Jeff Yoon8154e582019-12-03 23:30:011184 def resolve_matrix_compound_test_suites(self):
Jeff Yoon67c3e832020-02-08 07:39:381185 self.check_composition_type_test_suites('matrix_compound_suites',
1186 [check_matrix_identifier])
Jeff Yoon8154e582019-12-03 23:30:011187
1188 matrix_compound_suites = self.test_suites.get('matrix_compound_suites', {})
Jeff Yoon67c3e832020-02-08 07:39:381189 # check_composition_type_test_suites() checks that all basic suites are
Jeff Yoon8154e582019-12-03 23:30:011190 # referenced by matrix suites exist.
1191 basic_suites = self.test_suites.get('basic_suites')
1192
Garrett Beaty235c1412023-08-29 20:26:291193 for matrix_suite_name, matrix_config in matrix_compound_suites.items():
Jeff Yoon8154e582019-12-03 23:30:011194 full_suite = {}
Jeff Yoon67c3e832020-02-08 07:39:381195
Jamie Madillcf4f8c72021-05-20 19:24:231196 for test_suite, mtx_test_suite_config in matrix_config.items():
Jeff Yoon67c3e832020-02-08 07:39:381197 basic_test_def = copy.deepcopy(basic_suites[test_suite])
1198
Garrett Beaty235c1412023-08-29 20:26:291199 def update_tests(expanded):
1200 for test_name, new_tests in expanded.items():
1201 if not isinstance(new_tests, list):
1202 new_tests = [new_tests]
1203 tests_for_name = full_suite.setdefault(test_name, [])
1204 for t in new_tests:
1205 if t not in tests_for_name:
1206 tests_for_name.append(t)
1207
Garrett Beaty60a7b2a2023-09-13 23:00:401208 if (variants := mtx_test_suite_config.get('variants')):
Jeff Yoon85fb8df2020-08-20 16:47:431209 mixins = mtx_test_suite_config.get('mixins', [])
Garrett Beaty60a7b2a2023-09-13 23:00:401210 result = self.resolve_variants(basic_test_def, variants, mixins)
Garrett Beaty235c1412023-08-29 20:26:291211 update_tests(result)
Sven Zheng2fe6dd6f2021-08-06 21:12:271212 else:
1213 suite = basic_suites[test_suite]
Garrett Beaty235c1412023-08-29 20:26:291214 update_tests(suite)
1215 matrix_compound_suites[matrix_suite_name] = full_suite
Kenneth Russelleb60cbd22017-12-05 07:54:281216
1217 def link_waterfalls_to_test_suites(self):
1218 for waterfall in self.waterfalls:
Jamie Madillcf4f8c72021-05-20 19:24:231219 for tester_name, tester in waterfall['machines'].items():
1220 for suite, value in tester.get('test_suites', {}).items():
Kenneth Russelleb60cbd22017-12-05 07:54:281221 if not value in self.test_suites:
1222 # Hard / impossible to cover this in the unit test.
1223 raise self.unknown_test_suite(
1224 value, tester_name, waterfall['name']) # pragma: no cover
1225 tester['test_suites'][suite] = self.test_suites[value]
1226
1227 def load_configuration_files(self):
Garrett Beaty79339e182023-04-10 20:45:471228 self.waterfalls = self.load_pyl_file(self.args.waterfalls_pyl_path)
1229 self.test_suites = self.load_pyl_file(self.args.test_suites_pyl_path)
1230 self.exceptions = self.load_pyl_file(
1231 self.args.test_suite_exceptions_pyl_path)
1232 self.mixins = self.load_pyl_file(self.args.mixins_pyl_path)
1233 self.gn_isolate_map = self.load_pyl_file(self.args.gn_isolate_map_pyl_path)
Chong Guee622242020-10-28 18:17:351234 for isolate_map in self.args.isolate_map_files:
1235 isolate_map = self.load_pyl_file(isolate_map)
1236 duplicates = set(isolate_map).intersection(self.gn_isolate_map)
1237 if duplicates:
1238 raise BBGenErr('Duplicate targets in isolate map files: %s.' %
1239 ', '.join(duplicates))
1240 self.gn_isolate_map.update(isolate_map)
1241
Garrett Beaty79339e182023-04-10 20:45:471242 self.variants = self.load_pyl_file(self.args.variants_pyl_path)
Kenneth Russelleb60cbd22017-12-05 07:54:281243
1244 def resolve_configuration_files(self):
Garrett Beaty235c1412023-08-29 20:26:291245 self.resolve_test_names()
Garrett Beatydca3d882023-09-14 23:50:321246 self.resolve_isolate_names()
Garrett Beaty65d44222023-08-01 17:22:111247 self.resolve_dimension_sets()
Chan Lia3ad1502020-04-28 05:32:111248 self.resolve_test_id_prefixes()
Kenneth Russelleb60cbd22017-12-05 07:54:281249 self.resolve_composition_test_suites()
Jeff Yoon8154e582019-12-03 23:30:011250 self.resolve_matrix_compound_test_suites()
1251 self.flatten_test_suites()
Kenneth Russelleb60cbd22017-12-05 07:54:281252 self.link_waterfalls_to_test_suites()
1253
Garrett Beaty235c1412023-08-29 20:26:291254 def resolve_test_names(self):
1255 for suite_name, suite in self.test_suites.get('basic_suites').items():
1256 for test_name, test in suite.items():
1257 if 'name' in test:
1258 raise BBGenErr(
1259 f'The name field is set in test {test_name} in basic suite '
1260 f'{suite_name}, this is not supported, the test name is the key '
1261 'within the basic suite')
Garrett Beatyffe83c4f2023-09-08 19:07:371262 # When a test is expanded with variants, this will be overwritten, but
1263 # this ensures every test definition has the name field set
1264 test['name'] = test_name
Garrett Beaty235c1412023-08-29 20:26:291265
Garrett Beatydca3d882023-09-14 23:50:321266 def resolve_isolate_names(self):
1267 for suite_name, suite in self.test_suites.get('basic_suites').items():
1268 for test_name, test in suite.items():
1269 if 'isolate_name' in test:
1270 raise BBGenErr(
1271 f'The isolate_name field is set in test {test_name} in basic '
1272 f'suite {suite_name}, the test field should be used instead')
1273
Garrett Beaty65d44222023-08-01 17:22:111274 def resolve_dimension_sets(self):
Garrett Beaty65d44222023-08-01 17:22:111275
1276 def definitions():
1277 for suite_name, suite in self.test_suites.get('basic_suites', {}).items():
1278 for test_name, test in suite.items():
1279 yield test, f'test {test_name} in basic suite {suite_name}'
1280
1281 for mixin_name, mixin in self.mixins.items():
1282 yield mixin, f'mixin {mixin_name}'
1283
1284 for waterfall in self.waterfalls:
1285 for builder_name, builder in waterfall.get('machines', {}).items():
1286 yield (
1287 builder,
1288 f'builder {builder_name} in waterfall {waterfall["name"]}',
1289 )
1290
1291 for test_name, exceptions in self.exceptions.items():
1292 modifications = exceptions.get('modifications', {})
1293 for builder_name, mods in modifications.items():
1294 yield (
1295 mods,
1296 f'exception for test {test_name} on builder {builder_name}',
1297 )
1298
1299 for definition, location in definitions():
1300 for swarming_attr in (
1301 'swarming',
1302 'android_swarming',
1303 'chromeos_swarming',
1304 ):
1305 if (swarming :=
1306 definition.get(swarming_attr)) and 'dimension_sets' in swarming:
Garrett Beatyade673d2023-08-04 22:00:251307 raise BBGenErr(
1308 f'dimension_sets is no longer supported (set in {location}),'
1309 ' instead, use set dimensions to a single dict')
Garrett Beaty65d44222023-08-01 17:22:111310
Nico Weberd18b8962018-05-16 19:39:381311 def unknown_bot(self, bot_name, waterfall_name):
1312 return BBGenErr(
1313 'Unknown bot name "%s" on waterfall "%s"' % (bot_name, waterfall_name))
1314
Kenneth Russelleb60cbd22017-12-05 07:54:281315 def unknown_test_suite(self, suite_name, bot_name, waterfall_name):
1316 return BBGenErr(
Nico Weberd18b8962018-05-16 19:39:381317 'Test suite %s from machine %s on waterfall %s not present in '
Kenneth Russelleb60cbd22017-12-05 07:54:281318 'test_suites.pyl' % (suite_name, bot_name, waterfall_name))
1319
1320 def unknown_test_suite_type(self, suite_type, bot_name, waterfall_name):
1321 return BBGenErr(
1322 'Unknown test suite type ' + suite_type + ' in bot ' + bot_name +
1323 ' on waterfall ' + waterfall_name)
1324
Stephen Martinisb72f6d22018-10-04 23:29:011325 def apply_all_mixins(self, test, waterfall, builder_name, builder):
Stephen Martinis0382bc12018-09-17 22:29:071326 """Applies all present swarming mixins to the test for a given builder.
Stephen Martinisb6a50492018-09-12 23:59:321327
1328 Checks in the waterfall, builder, and test objects for mixins.
1329 """
1330 def valid_mixin(mixin_name):
1331 """Asserts that the mixin is valid."""
Stephen Martinisb72f6d22018-10-04 23:29:011332 if mixin_name not in self.mixins:
Stephen Martinisb6a50492018-09-12 23:59:321333 raise BBGenErr("bad mixin %s" % mixin_name)
Jeff Yoon67c3e832020-02-08 07:39:381334
Stephen Martinisb6a50492018-09-12 23:59:321335 def must_be_list(mixins, typ, name):
1336 """Asserts that given mixins are a list."""
1337 if not isinstance(mixins, list):
1338 raise BBGenErr("'%s' in %s '%s' must be a list" % (mixins, typ, name))
1339
Garrett Beatyffe83c4f2023-09-08 19:07:371340 test_name = test['name']
Brian Sheedy7658c982020-01-08 02:27:581341 remove_mixins = set()
1342 if 'remove_mixins' in builder:
1343 must_be_list(builder['remove_mixins'], 'builder', builder_name)
1344 for rm in builder['remove_mixins']:
1345 valid_mixin(rm)
1346 remove_mixins.add(rm)
1347 if 'remove_mixins' in test:
1348 must_be_list(test['remove_mixins'], 'test', test_name)
1349 for rm in test['remove_mixins']:
1350 valid_mixin(rm)
1351 remove_mixins.add(rm)
1352 del test['remove_mixins']
1353
Stephen Martinisb72f6d22018-10-04 23:29:011354 if 'mixins' in waterfall:
1355 must_be_list(waterfall['mixins'], 'waterfall', waterfall['name'])
1356 for mixin in waterfall['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581357 if mixin in remove_mixins:
1358 continue
Stephen Martinisb6a50492018-09-12 23:59:321359 valid_mixin(mixin)
Austin Eng148d9f0f2022-02-08 19:18:531360 test = self.apply_mixin(self.mixins[mixin], test, builder)
Stephen Martinisb6a50492018-09-12 23:59:321361
Stephen Martinisb72f6d22018-10-04 23:29:011362 if 'mixins' in builder:
1363 must_be_list(builder['mixins'], 'builder', builder_name)
1364 for mixin in builder['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581365 if mixin in remove_mixins:
1366 continue
Stephen Martinisb6a50492018-09-12 23:59:321367 valid_mixin(mixin)
Austin Eng148d9f0f2022-02-08 19:18:531368 test = self.apply_mixin(self.mixins[mixin], test, builder)
Stephen Martinisb6a50492018-09-12 23:59:321369
Stephen Martinisb72f6d22018-10-04 23:29:011370 if not 'mixins' in test:
Stephen Martinis0382bc12018-09-17 22:29:071371 return test
1372
Stephen Martinisb72f6d22018-10-04 23:29:011373 must_be_list(test['mixins'], 'test', test_name)
1374 for mixin in test['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581375 # We don't bother checking if the given mixin is in remove_mixins here
1376 # since this is already the lowest level, so if a mixin is added here that
1377 # we don't want, we can just delete its entry.
Stephen Martinis0382bc12018-09-17 22:29:071378 valid_mixin(mixin)
Austin Eng148d9f0f2022-02-08 19:18:531379 test = self.apply_mixin(self.mixins[mixin], test, builder)
Jeff Yoon67c3e832020-02-08 07:39:381380 del test['mixins']
Stephen Martinis0382bc12018-09-17 22:29:071381 return test
Stephen Martinisb6a50492018-09-12 23:59:321382
Garrett Beaty8d6708c2023-07-20 17:20:411383 def apply_mixin(self, mixin, test, builder=None):
Stephen Martinisb72f6d22018-10-04 23:29:011384 """Applies a mixin to a test.
Stephen Martinisb6a50492018-09-12 23:59:321385
Garrett Beaty4c35b142023-06-23 21:01:231386 A mixin is applied by copying all fields from the mixin into the
1387 test with the following exceptions:
1388 * For the various *args keys, the test's existing value (an empty
1389 list if not present) will be extended with the mixin's value.
1390 * The sub-keys of the swarming value will be copied to the test's
1391 swarming value with the following exceptions:
Garrett Beatyade673d2023-08-04 22:00:251392 * For the named_caches sub-keys, the test's existing value (an
1393 empty list if not present) will be extended with the mixin's
1394 value.
1395 * For the dimensions sub-key, the tests's existing value (an empty
1396 dict if not present) will be updated with the mixin's value.
Stephen Martinisb6a50492018-09-12 23:59:321397 """
Garrett Beaty4c35b142023-06-23 21:01:231398
Stephen Martinisb6a50492018-09-12 23:59:321399 new_test = copy.deepcopy(test)
1400 mixin = copy.deepcopy(mixin)
Garrett Beaty8d6708c2023-07-20 17:20:411401
1402 if 'description' in mixin:
1403 description = []
1404 if 'description' in new_test:
1405 description.append(new_test['description'])
1406 description.append(mixin.pop('description'))
1407 new_test['description'] = '\n'.join(description)
1408
Stephen Martinisb72f6d22018-10-04 23:29:011409 if 'swarming' in mixin:
1410 swarming_mixin = mixin['swarming']
1411 new_test.setdefault('swarming', {})
Stephen Martinisb72f6d22018-10-04 23:29:011412 if 'dimensions' in swarming_mixin:
Garrett Beatyade673d2023-08-04 22:00:251413 new_test['swarming'].setdefault('dimensions', {}).update(
1414 swarming_mixin.pop('dimensions'))
Garrett Beaty4c35b142023-06-23 21:01:231415 if 'named_caches' in swarming_mixin:
1416 new_test['swarming'].setdefault('named_caches', []).extend(
1417 swarming_mixin['named_caches'])
1418 del swarming_mixin['named_caches']
Stephen Martinisb72f6d22018-10-04 23:29:011419 # python dict update doesn't do recursion at all. Just hard code the
1420 # nested update we need (mixin['swarming'] shouldn't clobber
1421 # test['swarming'], but should update it).
1422 new_test['swarming'].update(swarming_mixin)
1423 del mixin['swarming']
1424
Garrett Beaty4c35b142023-06-23 21:01:231425 # Array so we can assign to it in a nested scope.
1426 args_need_fixup = ['args' in mixin]
1427
1428 for a in (
1429 'args',
1430 'precommit_args',
1431 'non_precommit_args',
1432 'desktop_args',
1433 'lacros_args',
1434 'linux_args',
1435 'android_args',
1436 'chromeos_args',
1437 'mac_args',
1438 'win_args',
1439 'win64_args',
1440 ):
1441 if (value := mixin.pop(a, None)) is None:
1442 continue
1443 if not isinstance(value, list):
1444 raise BBGenErr(f'"{a}" must be a list')
1445 new_test.setdefault(a, []).extend(value)
1446
Garrett Beaty4c35b142023-06-23 21:01:231447 args = new_test.get('args', [])
Austin Eng148d9f0f2022-02-08 19:18:531448
Garrett Beaty4c35b142023-06-23 21:01:231449 def add_conditional_args(key, fn):
Garrett Beaty8d6708c2023-07-20 17:20:411450 if builder is None:
1451 return
Garrett Beaty4c35b142023-06-23 21:01:231452 val = new_test.pop(key, [])
1453 if val and fn(builder):
1454 args.extend(val)
1455 args_need_fixup[0] = True
Austin Eng148d9f0f2022-02-08 19:18:531456
Garrett Beaty4c35b142023-06-23 21:01:231457 add_conditional_args('desktop_args', lambda cfg: not self.is_android(cfg))
1458 add_conditional_args('lacros_args', self.is_lacros)
1459 add_conditional_args('linux_args', self.is_linux)
1460 add_conditional_args('android_args', self.is_android)
1461 add_conditional_args('chromeos_args', self.is_chromeos)
1462 add_conditional_args('mac_args', self.is_mac)
1463 add_conditional_args('win_args', self.is_win)
1464 add_conditional_args('win64_args', self.is_win64)
1465
1466 if args_need_fixup[0]:
1467 new_test['args'] = self.maybe_fixup_args_array(args)
Wezc0e835b702018-10-30 00:38:411468
Stephen Martinisb72f6d22018-10-04 23:29:011469 new_test.update(mixin)
Stephen Martinisb6a50492018-09-12 23:59:321470 return new_test
1471
Greg Gutermanf60eb052020-03-12 17:40:011472 def generate_output_tests(self, waterfall):
1473 """Generates the tests for a waterfall.
1474
1475 Args:
1476 waterfall: a dictionary parsed from a master pyl file
1477 Returns:
1478 A dictionary mapping builders to test specs
1479 """
1480 return {
Jamie Madillcf4f8c72021-05-20 19:24:231481 name: self.get_tests_for_config(waterfall, name, config)
1482 for name, config in waterfall['machines'].items()
Greg Gutermanf60eb052020-03-12 17:40:011483 }
1484
1485 def get_tests_for_config(self, waterfall, name, config):
Greg Guterman5c6144152020-02-28 20:08:531486 generator_map = self.get_test_generator_map()
1487 test_type_remapper = self.get_test_type_remapper()
Kenneth Russelleb60cbd22017-12-05 07:54:281488
Greg Gutermanf60eb052020-03-12 17:40:011489 tests = {}
1490 # Copy only well-understood entries in the machine's configuration
1491 # verbatim into the generated JSON.
1492 if 'additional_compile_targets' in config:
1493 tests['additional_compile_targets'] = config[
1494 'additional_compile_targets']
Jamie Madillcf4f8c72021-05-20 19:24:231495 for test_type, input_tests in config.get('test_suites', {}).items():
Greg Gutermanf60eb052020-03-12 17:40:011496 if test_type not in generator_map:
1497 raise self.unknown_test_suite_type(
1498 test_type, name, waterfall['name']) # pragma: no cover
1499 test_generator = generator_map[test_type]
1500 # Let multiple kinds of generators generate the same kinds
1501 # of tests. For example, gpu_telemetry_tests are a
1502 # specialization of isolated_scripts.
1503 new_tests = test_generator.generate(
1504 waterfall, name, config, input_tests)
1505 remapped_test_type = test_type_remapper.get(test_type, test_type)
Garrett Beatyffe83c4f2023-09-08 19:07:371506 tests.setdefault(remapped_test_type, []).extend(new_tests)
1507
1508 for test_type, tests_for_type in tests.items():
1509 if test_type == 'additional_compile_targets':
1510 continue
1511 tests[test_type] = sorted(tests_for_type, key=lambda t: t['name'])
Greg Gutermanf60eb052020-03-12 17:40:011512
1513 return tests
1514
1515 def jsonify(self, all_tests):
1516 return json.dumps(
1517 all_tests, indent=2, separators=(',', ': '),
1518 sort_keys=True) + '\n'
1519
1520 def generate_outputs(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281521 self.load_configuration_files()
1522 self.resolve_configuration_files()
1523 filters = self.args.waterfall_filters
Greg Gutermanf60eb052020-03-12 17:40:011524 result = collections.defaultdict(dict)
1525
Stephanie Kim572b43c02023-04-13 14:24:131526 if os.path.exists(self.args.autoshard_exceptions_json_path):
1527 autoshards = json.loads(
1528 self.read_file(self.args.autoshard_exceptions_json_path))
1529 else:
1530 autoshards = {}
1531
Dirk Pranke6269d302020-10-01 00:14:391532 required_fields = ('name',)
Greg Gutermanf60eb052020-03-12 17:40:011533 for waterfall in self.waterfalls:
1534 for field in required_fields:
1535 # Verify required fields
1536 if field not in waterfall:
1537 raise BBGenErr("Waterfall %s has no %s" % (waterfall['name'], field))
1538
1539 # Handle filter flag, if specified
1540 if filters and waterfall['name'] not in filters:
1541 continue
1542
1543 # Join config files and hardcoded values together
1544 all_tests = self.generate_output_tests(waterfall)
1545 result[waterfall['name']] = all_tests
1546
Stephanie Kim572b43c02023-04-13 14:24:131547 if not autoshards:
1548 continue
1549 for builder, test_spec in all_tests.items():
1550 for target_type, test_list in test_spec.items():
1551 if target_type == 'additional_compile_targets':
1552 continue
1553 for test_dict in test_list:
1554 # Suites that apply variants or other customizations will create
1555 # test_dicts that have "name" value that is different from the
Garrett Beatyffe83c4f2023-09-08 19:07:371556 # "test" value.
Stephanie Kim572b43c02023-04-13 14:24:131557 # e.g. name = vulkan_swiftshader_content_browsertests, but
1558 # test = content_browsertests and
1559 # test_id_prefix = "ninja://content/test:content_browsertests/"
Garrett Beatyffe83c4f2023-09-08 19:07:371560 test_name = test_dict['name']
Stephanie Kim572b43c02023-04-13 14:24:131561 shard_info = autoshards.get(waterfall['name'],
1562 {}).get(builder, {}).get(test_name)
1563 if shard_info:
1564 test_dict['swarming'].update(
1565 {'shards': int(shard_info['shards'])})
1566
Greg Gutermanf60eb052020-03-12 17:40:011567 # Add do not edit warning
1568 for tests in result.values():
1569 tests['AAAAA1 AUTOGENERATED FILE DO NOT EDIT'] = {}
1570 tests['AAAAA2 See generate_buildbot_json.py to make changes'] = {}
1571
1572 return result
1573
1574 def write_json_result(self, result): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281575 suffix = '.json'
1576 if self.args.new_files:
1577 suffix = '.new' + suffix
Greg Gutermanf60eb052020-03-12 17:40:011578
1579 for filename, contents in result.items():
1580 jsonstr = self.jsonify(contents)
Garrett Beaty79339e182023-04-10 20:45:471581 file_path = os.path.join(self.args.output_dir, filename + suffix)
1582 self.write_file(file_path, jsonstr)
Kenneth Russelleb60cbd22017-12-05 07:54:281583
Nico Weberd18b8962018-05-16 19:39:381584 def get_valid_bot_names(self):
Garrett Beatyff6e98d2021-09-02 17:00:161585 # Extract bot names from infra/config/generated/luci/luci-milo.cfg.
Stephen Martinis26627cf2018-12-19 01:51:421586 # NOTE: This reference can cause issues; if a file changes there, the
1587 # presubmit here won't be run by default. A manually maintained list there
1588 # tries to run presubmit here when luci-milo.cfg is changed. If any other
1589 # references to configs outside of this directory are added, please change
1590 # their presubmit to run `generate_buildbot_json.py -c`, so that the tree
1591 # never ends up in an invalid state.
Garrett Beaty4f3e9212020-06-25 20:21:491592
Garrett Beaty7e866fc2021-06-16 14:12:101593 # Get the generated project.pyl so we can check if we should be enforcing
1594 # that the specs are for builders that actually exist
1595 # If not, return None to indicate that we won't enforce that builders in
1596 # waterfalls.pyl are defined in LUCI
Garrett Beaty4f3e9212020-06-25 20:21:491597 project_pyl_path = os.path.join(self.args.infra_config_dir, 'generated',
1598 'project.pyl')
1599 if os.path.exists(project_pyl_path):
1600 settings = ast.literal_eval(self.read_file(project_pyl_path))
1601 if not settings.get('validate_source_side_specs_have_builder', True):
1602 return None
1603
Nico Weberd18b8962018-05-16 19:39:381604 bot_names = set()
Garrett Beatyd5ca75962020-05-07 16:58:311605 milo_configs = glob.glob(
Garrett Beatyff6e98d2021-09-02 17:00:161606 os.path.join(self.args.infra_config_dir, 'generated', 'luci',
1607 'luci-milo*.cfg'))
John Budorickc12abd12018-08-14 19:37:431608 for c in milo_configs:
1609 for l in self.read_file(c).splitlines():
1610 if (not 'name: "buildbucket/luci.chromium.' in l and
Garrett Beatyd5ca75962020-05-07 16:58:311611 not 'name: "buildbucket/luci.chrome.' in l):
John Budorickc12abd12018-08-14 19:37:431612 continue
1613 # l looks like
1614 # `name: "buildbucket/luci.chromium.try/win_chromium_dbg_ng"`
1615 # Extract win_chromium_dbg_ng part.
1616 bot_names.add(l[l.rindex('/') + 1:l.rindex('"')])
Nico Weberd18b8962018-05-16 19:39:381617 return bot_names
1618
Ben Pastene9a010082019-09-25 20:41:371619 def get_internal_waterfalls(self):
1620 # Similar to get_builders_that_do_not_actually_exist above, but for
1621 # waterfalls defined in internal configs.
Yuke Liaoe6c23dd2021-07-28 16:12:201622 return [
Kramer Ge3bf853a2023-04-13 19:39:471623 'chrome', 'chrome.pgo', 'chrome.gpu.fyi', 'internal.chrome.fyi',
yoshiki iguchi4de608082024-03-14 00:33:361624 'internal.chromeos.fyi', 'internal.optimization_guide', 'internal.soda',
1625 'chromeos.preuprev'
Yuke Liaoe6c23dd2021-07-28 16:12:201626 ]
Ben Pastene9a010082019-09-25 20:41:371627
Stephen Martinisf83893722018-09-19 00:02:181628 def check_input_file_consistency(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201629 self.check_input_files_sorting(verbose)
1630
Kenneth Russelleb60cbd22017-12-05 07:54:281631 self.load_configuration_files()
Jeff Yoon8154e582019-12-03 23:30:011632 self.check_composition_type_test_suites('compound_suites')
Jeff Yoon67c3e832020-02-08 07:39:381633 self.check_composition_type_test_suites('matrix_compound_suites',
1634 [check_matrix_identifier])
Chan Lia3ad1502020-04-28 05:32:111635 self.resolve_test_id_prefixes()
Garrett Beaty1ead4a52023-12-07 19:16:421636
1637 # All test suites must be referenced. Check this before flattening the test
1638 # suites so that we can transitively check the basic suites for compound
1639 # suites and matrix compound suites (otherwise we would determine a basic
1640 # suite is used if it shared a name with a test present in a basic suite
1641 # that is used).
1642 all_suites = set(
1643 itertools.chain(*(self.test_suites.get(a, {}) for a in (
1644 'basic_suites',
1645 'compound_suites',
1646 'matrix_compound_suites',
1647 ))))
1648 unused_suites = set(all_suites)
1649 generator_map = self.get_test_generator_map()
1650 for waterfall in self.waterfalls:
1651 for bot_name, tester in waterfall['machines'].items():
1652 for suite_type, suite in tester.get('test_suites', {}).items():
1653 if suite_type not in generator_map:
1654 raise self.unknown_test_suite_type(suite_type, bot_name,
1655 waterfall['name'])
1656 if suite not in all_suites:
1657 raise self.unknown_test_suite(suite, bot_name, waterfall['name'])
1658 unused_suites.discard(suite)
1659 # For each compound suite or matrix compound suite, if the suite was used,
1660 # remove all of the basic suites that it composes from the set of unused
1661 # suites
1662 for a in ('compound_suites', 'matrix_compound_suites'):
1663 for suite, sub_suites in self.test_suites.get(a, {}).items():
1664 if suite not in unused_suites:
1665 unused_suites.difference_update(sub_suites)
1666 if unused_suites:
1667 raise BBGenErr('The following test suites were unreferenced by bots on '
1668 'the waterfalls: ' + str(unused_suites))
1669
Stephen Martinis54d64ad2018-09-21 22:16:201670 self.flatten_test_suites()
Nico Weberd18b8962018-05-16 19:39:381671
1672 # All bots should exist.
1673 bot_names = self.get_valid_bot_names()
Garrett Beaty2a02de3c2020-05-15 13:57:351674 if bot_names is not None:
1675 internal_waterfalls = self.get_internal_waterfalls()
1676 for waterfall in self.waterfalls:
1677 # TODO(crbug.com/991417): Remove the need for this exception.
1678 if waterfall['name'] in internal_waterfalls:
Kenneth Russell8a386d42018-06-02 09:48:011679 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351680 for bot_name in waterfall['machines']:
Garrett Beaty2a02de3c2020-05-15 13:57:351681 if bot_name not in bot_names:
Garrett Beatyb9895922022-04-18 23:34:581682 if waterfall['name'] in [
1683 'client.v8.chromium', 'client.v8.fyi', 'tryserver.v8'
1684 ]:
Garrett Beaty2a02de3c2020-05-15 13:57:351685 # TODO(thakis): Remove this once these bots move to luci.
1686 continue # pragma: no cover
1687 if waterfall['name'] in ['tryserver.webrtc',
1688 'webrtc.chromium.fyi.experimental']:
1689 # These waterfalls have their bot configs in a different repo.
1690 # so we don't know about their bot names.
1691 continue # pragma: no cover
1692 if waterfall['name'] in ['client.devtools-frontend.integration',
1693 'tryserver.devtools-frontend',
1694 'chromium.devtools-frontend']:
1695 continue # pragma: no cover
Garrett Beaty48d261a2020-09-17 22:11:201696 if waterfall['name'] in ['client.openscreen.chromium']:
1697 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351698 raise self.unknown_bot(bot_name, waterfall['name'])
Nico Weberd18b8962018-05-16 19:39:381699
Kenneth Russelleb60cbd22017-12-05 07:54:281700 # All test suite exceptions must refer to bots on the waterfall.
1701 all_bots = set()
1702 missing_bots = set()
1703 for waterfall in self.waterfalls:
Jamie Madillcf4f8c72021-05-20 19:24:231704 for bot_name, tester in waterfall['machines'].items():
Kenneth Russelleb60cbd22017-12-05 07:54:281705 all_bots.add(bot_name)
Kenneth Russell8ceeabf2017-12-11 17:53:281706 # In order to disambiguate between bots with the same name on
1707 # different waterfalls, support has been added to various
1708 # exceptions for concatenating the waterfall name after the bot
1709 # name.
1710 all_bots.add(bot_name + ' ' + waterfall['name'])
Jamie Madillcf4f8c72021-05-20 19:24:231711 for exception in self.exceptions.values():
Nico Weberd18b8962018-05-16 19:39:381712 removals = (exception.get('remove_from', []) +
1713 exception.get('remove_gtest_from', []) +
Jamie Madillcf4f8c72021-05-20 19:24:231714 list(exception.get('modifications', {}).keys()))
Nico Weberd18b8962018-05-16 19:39:381715 for removal in removals:
Kenneth Russelleb60cbd22017-12-05 07:54:281716 if removal not in all_bots:
1717 missing_bots.add(removal)
Stephen Martiniscc70c962018-07-31 21:22:411718
Kenneth Russelleb60cbd22017-12-05 07:54:281719 if missing_bots:
1720 raise BBGenErr('The following nonexistent machines were referenced in '
1721 'the test suite exceptions: ' + str(missing_bots))
1722
Garrett Beatyb061e69d2023-06-27 16:15:351723 for name, mixin in self.mixins.items():
1724 if '$mixin_append' in mixin:
1725 raise BBGenErr(
1726 f'$mixin_append is no longer supported (set in mixin "{name}"),'
1727 ' args and named caches specified as normal will be appended')
1728
Stephen Martinis0382bc12018-09-17 22:29:071729 # All mixins must be referenced
1730 seen_mixins = set()
1731 for waterfall in self.waterfalls:
Stephen Martinisb72f6d22018-10-04 23:29:011732 seen_mixins = seen_mixins.union(waterfall.get('mixins', set()))
Jamie Madillcf4f8c72021-05-20 19:24:231733 for bot_name, tester in waterfall['machines'].items():
Stephen Martinisb72f6d22018-10-04 23:29:011734 seen_mixins = seen_mixins.union(tester.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071735 for suite in self.test_suites.values():
1736 if isinstance(suite, list):
1737 # Don't care about this, it's a composition, which shouldn't include a
1738 # swarming mixin.
1739 continue
1740
1741 for test in suite.values():
Dirk Pranke0e879b22020-07-16 23:53:561742 assert isinstance(test, dict)
Stephen Martinisb72f6d22018-10-04 23:29:011743 seen_mixins = seen_mixins.union(test.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071744
Zhaoyang Li9da047d52021-05-10 21:31:441745 for variant in self.variants:
1746 # Unpack the variant from variants.pyl if it's string based.
1747 if isinstance(variant, str):
1748 variant = self.variants[variant]
1749 seen_mixins = seen_mixins.union(variant.get('mixins', set()))
1750
Stephen Martinisb72f6d22018-10-04 23:29:011751 missing_mixins = set(self.mixins.keys()) - seen_mixins
Stephen Martinis0382bc12018-09-17 22:29:071752 if missing_mixins:
1753 raise BBGenErr('The following mixins are unreferenced: %s. They must be'
1754 ' referenced in a waterfall, machine, or test suite.' % (
1755 str(missing_mixins)))
1756
Jeff Yoonda581c32020-03-06 03:56:051757 # All variant references must be referenced
1758 seen_variants = set()
1759 for suite in self.test_suites.values():
1760 if isinstance(suite, list):
1761 continue
1762
1763 for test in suite.values():
1764 if isinstance(test, dict):
1765 for variant in test.get('variants', []):
1766 if isinstance(variant, str):
1767 seen_variants.add(variant)
1768
1769 missing_variants = set(self.variants.keys()) - seen_variants
1770 if missing_variants:
1771 raise BBGenErr('The following variants were unreferenced: %s. They must '
1772 'be referenced in a matrix test suite under the variants '
1773 'key.' % str(missing_variants))
1774
Stephen Martinis54d64ad2018-09-21 22:16:201775
Garrett Beaty79339e182023-04-10 20:45:471776 def type_assert(self, node, typ, file_path, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201777 """Asserts that the Python AST node |node| is of type |typ|.
1778
1779 If verbose is set, it prints out some helpful context lines, showing where
1780 exactly the error occurred in the file.
1781 """
1782 if not isinstance(node, typ):
1783 if verbose:
Garrett Beaty79339e182023-04-10 20:45:471784 lines = [""] + self.read_file(file_path).splitlines()
Stephen Martinis54d64ad2018-09-21 22:16:201785
1786 context = 2
1787 lines_start = max(node.lineno - context, 0)
1788 # Add one to include the last line
1789 lines_end = min(node.lineno + context, len(lines)) + 1
Garrett Beaty79339e182023-04-10 20:45:471790 lines = itertools.chain(
1791 ['== %s ==\n' % file_path],
1792 ["<snip>\n"],
1793 [
1794 '%d %s' % (lines_start + i, line)
1795 for i, line in enumerate(lines[lines_start:lines_start +
1796 context])
1797 ],
1798 ['-' * 80 + '\n'],
1799 ['%d %s' % (node.lineno, lines[node.lineno])],
1800 [
1801 '-' * (node.col_offset + 3) + '^' + '-' *
1802 (80 - node.col_offset - 4) + '\n'
1803 ],
1804 [
1805 '%d %s' % (node.lineno + 1 + i, line)
1806 for i, line in enumerate(lines[node.lineno + 1:lines_end])
1807 ],
1808 ["<snip>\n"],
Stephen Martinis54d64ad2018-09-21 22:16:201809 )
1810 # Print out a useful message when a type assertion fails.
1811 for l in lines:
1812 self.print_line(l.strip())
1813
1814 node_dumped = ast.dump(node, annotate_fields=False)
1815 # If the node is huge, truncate it so everything fits in a terminal
1816 # window.
1817 if len(node_dumped) > 60: # pragma: no cover
1818 node_dumped = node_dumped[:30] + ' <SNIP> ' + node_dumped[-30:]
1819 raise BBGenErr(
Garrett Beaty807011ab2023-04-12 00:52:391820 'Invalid .pyl file \'%s\'. Python AST node %r on line %s expected to'
Garrett Beaty79339e182023-04-10 20:45:471821 ' be %s, is %s' %
1822 (file_path, node_dumped, node.lineno, typ, type(node)))
Stephen Martinis54d64ad2018-09-21 22:16:201823
Garrett Beaty79339e182023-04-10 20:45:471824 def check_ast_list_formatted(self,
1825 keys,
1826 file_path,
1827 verbose,
Stephen Martinis1384ff92020-01-07 19:52:151828 check_sorting=True):
Stephen Martinis5bef0fc2020-01-06 22:47:531829 """Checks if a list of ast keys are correctly formatted.
Stephen Martinis54d64ad2018-09-21 22:16:201830
Stephen Martinis5bef0fc2020-01-06 22:47:531831 Currently only checks to ensure they're correctly sorted, and that there
1832 are no duplicates.
1833
1834 Args:
1835 keys: An python list of AST nodes.
1836
1837 It's a list of AST nodes instead of a list of strings because
1838 when verbose is set, it tries to print out context of where the
1839 diffs are in the file.
Garrett Beaty79339e182023-04-10 20:45:471840 file_path: The path to the file this node is from.
Stephen Martinis5bef0fc2020-01-06 22:47:531841 verbose: If set, print out diff information about how the keys are
1842 incorrectly formatted.
1843 check_sorting: If true, checks if the list is sorted.
1844 Returns:
1845 If the keys are correctly formatted.
1846 """
1847 if not keys:
1848 return True
1849
1850 assert isinstance(keys[0], ast.Str)
1851
1852 keys_strs = [k.s for k in keys]
1853 # Keys to diff against. Used below.
1854 keys_to_diff_against = None
1855 # If the list is properly formatted.
1856 list_formatted = True
1857
1858 # Duplicates are always bad.
1859 if len(set(keys_strs)) != len(keys_strs):
1860 list_formatted = False
1861 keys_to_diff_against = list(collections.OrderedDict.fromkeys(keys_strs))
1862
1863 if check_sorting and sorted(keys_strs) != keys_strs:
1864 list_formatted = False
1865 if list_formatted:
1866 return True
1867
1868 if verbose:
1869 line_num = keys[0].lineno
1870 keys = [k.s for k in keys]
1871 if check_sorting:
1872 # If we have duplicates, sorting this will take care of it anyways.
1873 keys_to_diff_against = sorted(set(keys))
1874 # else, keys_to_diff_against is set above already
1875
1876 self.print_line('=' * 80)
1877 self.print_line('(First line of keys is %s)' % line_num)
Garrett Beaty79339e182023-04-10 20:45:471878 for line in difflib.context_diff(keys,
1879 keys_to_diff_against,
1880 fromfile='current (%r)' % file_path,
1881 tofile='sorted',
1882 lineterm=''):
Stephen Martinis5bef0fc2020-01-06 22:47:531883 self.print_line(line)
1884 self.print_line('=' * 80)
1885
1886 return False
1887
Garrett Beaty79339e182023-04-10 20:45:471888 def check_ast_dict_formatted(self, node, file_path, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531889 """Checks if an ast dictionary's keys are correctly formatted.
1890
1891 Just a simple wrapper around check_ast_list_formatted.
1892 Args:
1893 node: An AST node. Assumed to be a dictionary.
Garrett Beaty79339e182023-04-10 20:45:471894 file_path: The path to the file this node is from.
Stephen Martinis5bef0fc2020-01-06 22:47:531895 verbose: If set, print out diff information about how the keys are
1896 incorrectly formatted.
1897 check_sorting: If true, checks if the list is sorted.
1898 Returns:
1899 If the dictionary is correctly formatted.
1900 """
Stephen Martinis54d64ad2018-09-21 22:16:201901 keys = []
1902 # The keys of this dict are ordered as ordered in the file; normal python
1903 # dictionary keys are given an arbitrary order, but since we parsed the
1904 # file itself, the order as given in the file is preserved.
1905 for key in node.keys:
Garrett Beaty79339e182023-04-10 20:45:471906 self.type_assert(key, ast.Str, file_path, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531907 keys.append(key)
Stephen Martinis54d64ad2018-09-21 22:16:201908
Garrett Beaty79339e182023-04-10 20:45:471909 return self.check_ast_list_formatted(keys, file_path, verbose)
Stephen Martinisf83893722018-09-19 00:02:181910
1911 def check_input_files_sorting(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201912 # TODO(https://crbug.com/886993): Add the ability for this script to
1913 # actually format the files, rather than just complain if they're
1914 # incorrectly formatted.
1915 bad_files = set()
Garrett Beaty79339e182023-04-10 20:45:471916
1917 def parse_file(file_path):
Stephen Martinis5bef0fc2020-01-06 22:47:531918 """Parses and validates a .pyl file.
Stephen Martinis54d64ad2018-09-21 22:16:201919
Stephen Martinis5bef0fc2020-01-06 22:47:531920 Returns an AST node representing the value in the pyl file."""
Garrett Beaty79339e182023-04-10 20:45:471921 parsed = ast.parse(self.read_file(file_path))
Stephen Martinisf83893722018-09-19 00:02:181922
Stephen Martinisf83893722018-09-19 00:02:181923 # Must be a module.
Garrett Beaty79339e182023-04-10 20:45:471924 self.type_assert(parsed, ast.Module, file_path, verbose)
Stephen Martinisf83893722018-09-19 00:02:181925 module = parsed.body
1926
1927 # Only one expression in the module.
Garrett Beaty79339e182023-04-10 20:45:471928 self.type_assert(module, list, file_path, verbose)
Stephen Martinisf83893722018-09-19 00:02:181929 if len(module) != 1: # pragma: no cover
Garrett Beaty79339e182023-04-10 20:45:471930 raise BBGenErr('Invalid .pyl file %s' % file_path)
Stephen Martinisf83893722018-09-19 00:02:181931 expr = module[0]
Garrett Beaty79339e182023-04-10 20:45:471932 self.type_assert(expr, ast.Expr, file_path, verbose)
Stephen Martinisf83893722018-09-19 00:02:181933
Stephen Martinis5bef0fc2020-01-06 22:47:531934 return expr.value
1935
1936 # Handle this separately
Garrett Beaty79339e182023-04-10 20:45:471937 value = parse_file(self.args.waterfalls_pyl_path)
Stephen Martinis5bef0fc2020-01-06 22:47:531938 # Value should be a list.
Garrett Beaty79339e182023-04-10 20:45:471939 self.type_assert(value, ast.List, self.args.waterfalls_pyl_path, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531940
1941 keys = []
Joshua Hood56c673c2022-03-02 20:29:331942 for elm in value.elts:
Garrett Beaty79339e182023-04-10 20:45:471943 self.type_assert(elm, ast.Dict, self.args.waterfalls_pyl_path, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531944 waterfall_name = None
Joshua Hood56c673c2022-03-02 20:29:331945 for key, val in zip(elm.keys, elm.values):
Garrett Beaty79339e182023-04-10 20:45:471946 self.type_assert(key, ast.Str, self.args.waterfalls_pyl_path, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531947 if key.s == 'machines':
Garrett Beaty79339e182023-04-10 20:45:471948 if not self.check_ast_dict_formatted(
1949 val, self.args.waterfalls_pyl_path, verbose):
1950 bad_files.add(self.args.waterfalls_pyl_path)
Stephen Martinis5bef0fc2020-01-06 22:47:531951
1952 if key.s == "name":
Garrett Beaty79339e182023-04-10 20:45:471953 self.type_assert(val, ast.Str, self.args.waterfalls_pyl_path, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531954 waterfall_name = val
1955 assert waterfall_name
1956 keys.append(waterfall_name)
1957
Garrett Beaty79339e182023-04-10 20:45:471958 if not self.check_ast_list_formatted(keys, self.args.waterfalls_pyl_path,
1959 verbose):
1960 bad_files.add(self.args.waterfalls_pyl_path)
Stephen Martinis5bef0fc2020-01-06 22:47:531961
Garrett Beaty79339e182023-04-10 20:45:471962 for file_path in (
1963 self.args.mixins_pyl_path,
1964 self.args.test_suites_pyl_path,
1965 self.args.test_suite_exceptions_pyl_path,
Stephen Martinis5bef0fc2020-01-06 22:47:531966 ):
Garrett Beaty79339e182023-04-10 20:45:471967 value = parse_file(file_path)
Stephen Martinisf83893722018-09-19 00:02:181968 # Value should be a dictionary.
Garrett Beaty79339e182023-04-10 20:45:471969 self.type_assert(value, ast.Dict, file_path, verbose)
Stephen Martinisf83893722018-09-19 00:02:181970
Garrett Beaty79339e182023-04-10 20:45:471971 if not self.check_ast_dict_formatted(value, file_path, verbose):
1972 bad_files.add(file_path)
Stephen Martinis5bef0fc2020-01-06 22:47:531973
Garrett Beaty79339e182023-04-10 20:45:471974 if file_path == self.args.test_suites_pyl_path:
Jeff Yoon8154e582019-12-03 23:30:011975 expected_keys = ['basic_suites',
1976 'compound_suites',
1977 'matrix_compound_suites']
Stephen Martinis54d64ad2018-09-21 22:16:201978 actual_keys = [node.s for node in value.keys]
1979 assert all(key in expected_keys for key in actual_keys), (
Garrett Beaty79339e182023-04-10 20:45:471980 'Invalid %r file; expected keys %r, got %r' %
1981 (file_path, expected_keys, actual_keys))
Joshua Hood56c673c2022-03-02 20:29:331982 suite_dicts = list(value.values)
Stephen Martinis54d64ad2018-09-21 22:16:201983 # Only two keys should mean only 1 or 2 values
Jeff Yoon8154e582019-12-03 23:30:011984 assert len(suite_dicts) <= 3
Stephen Martinis54d64ad2018-09-21 22:16:201985 for suite_group in suite_dicts:
Garrett Beaty79339e182023-04-10 20:45:471986 if not self.check_ast_dict_formatted(suite_group, file_path, verbose):
1987 bad_files.add(file_path)
Stephen Martinisf83893722018-09-19 00:02:181988
Stephen Martinis5bef0fc2020-01-06 22:47:531989 for key, suite in zip(value.keys, value.values):
1990 # The compound suites are checked in
1991 # 'check_composition_type_test_suites()'
1992 if key.s == 'basic_suites':
1993 for group in suite.values:
Garrett Beaty79339e182023-04-10 20:45:471994 if not self.check_ast_dict_formatted(group, file_path, verbose):
1995 bad_files.add(file_path)
Stephen Martinis5bef0fc2020-01-06 22:47:531996 break
Stephen Martinis54d64ad2018-09-21 22:16:201997
Garrett Beaty79339e182023-04-10 20:45:471998 elif file_path == self.args.test_suite_exceptions_pyl_path:
Stephen Martinis5bef0fc2020-01-06 22:47:531999 # Check the values for each test.
2000 for test in value.values:
2001 for kind, node in zip(test.keys, test.values):
2002 if isinstance(node, ast.Dict):
Garrett Beaty79339e182023-04-10 20:45:472003 if not self.check_ast_dict_formatted(node, file_path, verbose):
2004 bad_files.add(file_path)
Stephen Martinis5bef0fc2020-01-06 22:47:532005 elif kind.s == 'remove_from':
2006 # Don't care about sorting; these are usually grouped, since the
2007 # same bug can affect multiple builders. Do want to make sure
2008 # there aren't duplicates.
Garrett Beaty79339e182023-04-10 20:45:472009 if not self.check_ast_list_formatted(
2010 node.elts, file_path, verbose, check_sorting=False):
2011 bad_files.add(file_path)
Stephen Martinisf83893722018-09-19 00:02:182012
2013 if bad_files:
2014 raise BBGenErr(
Stephen Martinis54d64ad2018-09-21 22:16:202015 'The following files have invalid keys: %s\n. They are either '
Stephen Martinis5bef0fc2020-01-06 22:47:532016 'unsorted, or have duplicates. Re-run this with --verbose to see '
2017 'more details.' % ', '.join(bad_files))
Stephen Martinisf83893722018-09-19 00:02:182018
Kenneth Russelleb60cbd22017-12-05 07:54:282019 def check_output_file_consistency(self, verbose=False):
2020 self.load_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:012021 # All waterfalls/bucket .json files must have been written
2022 # by this script already.
Kenneth Russelleb60cbd22017-12-05 07:54:282023 self.resolve_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:012024 ungenerated_files = set()
Dirk Pranke772f55f2021-04-28 04:51:162025 outputs = self.generate_outputs()
2026 for filename, expected_contents in outputs.items():
Greg Gutermanf60eb052020-03-12 17:40:012027 expected = self.jsonify(expected_contents)
Garrett Beaty79339e182023-04-10 20:45:472028 file_path = os.path.join(self.args.output_dir, filename + '.json')
Ben Pastenef21cda32023-03-30 22:00:572029 current = self.read_file(file_path)
Kenneth Russelleb60cbd22017-12-05 07:54:282030 if expected != current:
Greg Gutermanf60eb052020-03-12 17:40:012031 ungenerated_files.add(filename)
John Budorick826d5ed2017-12-28 19:27:322032 if verbose: # pragma: no cover
Greg Gutermanf60eb052020-03-12 17:40:012033 self.print_line('File ' + filename +
2034 '.json did not have the following expected '
John Budorick826d5ed2017-12-28 19:27:322035 'contents:')
2036 for line in difflib.unified_diff(
2037 expected.splitlines(),
Stephen Martinis7eb8b612018-09-21 00:17:502038 current.splitlines(),
2039 fromfile='expected', tofile='current'):
2040 self.print_line(line)
Greg Gutermanf60eb052020-03-12 17:40:012041
2042 if ungenerated_files:
2043 raise BBGenErr(
2044 'The following files have not been properly '
2045 'autogenerated by generate_buildbot_json.py: ' +
2046 ', '.join([filename + '.json' for filename in ungenerated_files]))
Kenneth Russelleb60cbd22017-12-05 07:54:282047
Dirk Pranke772f55f2021-04-28 04:51:162048 for builder_group, builders in outputs.items():
2049 for builder, step_types in builders.items():
Garrett Beatydca3d882023-09-14 23:50:322050 for test_type in ('gtest_tests', 'isolated_scripts'):
2051 for step_data in step_types.get(test_type, []):
2052 step_name = step_data['name']
2053 self._check_swarming_config(builder_group, builder, step_name,
2054 step_data)
Dirk Pranke772f55f2021-04-28 04:51:162055
2056 def _check_swarming_config(self, filename, builder, step_name, step_data):
Ben Pastene338f56b2023-03-31 21:24:452057 # TODO(crbug.com/1203436): Ensure all swarming tests specify cpu, not
Dirk Pranke772f55f2021-04-28 04:51:162058 # just mac tests.
Garrett Beatybb18d532023-06-26 22:16:332059 if 'swarming' in step_data:
Garrett Beatyade673d2023-08-04 22:00:252060 dimensions = step_data['swarming'].get('dimensions')
2061 if not dimensions:
Tatsuhisa Yamaguchif1878d52023-11-06 06:02:252062 raise BBGenErr('%s: %s / %s : dimensions must be specified for all '
Dirk Pranke772f55f2021-04-28 04:51:162063 'swarmed tests' % (filename, builder, step_name))
Garrett Beatyade673d2023-08-04 22:00:252064 if not dimensions.get('os'):
2065 raise BBGenErr('%s: %s / %s : os must be specified for all '
2066 'swarmed tests' % (filename, builder, step_name))
2067 if 'Mac' in dimensions.get('os') and not dimensions.get('cpu'):
2068 raise BBGenErr('%s: %s / %s : cpu must be specified for mac '
2069 'swarmed tests' % (filename, builder, step_name))
Dirk Pranke772f55f2021-04-28 04:51:162070
Kenneth Russelleb60cbd22017-12-05 07:54:282071 def check_consistency(self, verbose=False):
Stephen Martinis7eb8b612018-09-21 00:17:502072 self.check_input_file_consistency(verbose) # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:282073 self.check_output_file_consistency(verbose) # pragma: no cover
2074
Karen Qiane24b7ee2019-02-12 23:37:062075 def does_test_match(self, test_info, params_dict):
2076 """Checks to see if the test matches the parameters given.
2077
2078 Compares the provided test_info with the params_dict to see
2079 if the bot matches the parameters given. If so, returns True.
2080 Else, returns false.
2081
2082 Args:
2083 test_info (dict): Information about a specific bot provided
2084 in the format shown in waterfalls.pyl
2085 params_dict (dict): Dictionary of parameters and their values
2086 to look for in the bot
2087 Ex: {
2088 'device_os':'android',
2089 '--flag':True,
2090 'mixins': ['mixin1', 'mixin2'],
2091 'ex_key':'ex_value'
2092 }
2093
2094 """
2095 DIMENSION_PARAMS = ['device_os', 'device_type', 'os',
2096 'kvm', 'pool', 'integrity'] # dimension parameters
2097 SWARMING_PARAMS = ['shards', 'hard_timeout', 'idempotent',
2098 'can_use_on_swarming_builders']
2099 for param in params_dict:
2100 # if dimension parameter
2101 if param in DIMENSION_PARAMS or param in SWARMING_PARAMS:
2102 if not 'swarming' in test_info:
2103 return False
2104 swarming = test_info['swarming']
2105 if param in SWARMING_PARAMS:
2106 if not param in swarming:
2107 return False
2108 if not str(swarming[param]) == params_dict[param]:
2109 return False
2110 else:
Garrett Beatyade673d2023-08-04 22:00:252111 if not 'dimensions' in swarming:
Karen Qiane24b7ee2019-02-12 23:37:062112 return False
Garrett Beatyade673d2023-08-04 22:00:252113 dimensions = swarming['dimensions']
Karen Qiane24b7ee2019-02-12 23:37:062114 # only looking at the first dimension set
Garrett Beatyade673d2023-08-04 22:00:252115 if not param in dimensions:
Karen Qiane24b7ee2019-02-12 23:37:062116 return False
Garrett Beatyade673d2023-08-04 22:00:252117 if not dimensions[param] == params_dict[param]:
Karen Qiane24b7ee2019-02-12 23:37:062118 return False
2119
2120 # if flag
2121 elif param.startswith('--'):
2122 if not 'args' in test_info:
2123 return False
2124 if not param in test_info['args']:
2125 return False
2126
2127 # not dimension parameter/flag/mixin
2128 else:
2129 if not param in test_info:
2130 return False
2131 if not test_info[param] == params_dict[param]:
2132 return False
2133 return True
2134 def error_msg(self, msg):
2135 """Prints an error message.
2136
2137 In addition to a catered error message, also prints
2138 out where the user can find more help. Then, program exits.
2139 """
2140 self.print_line(msg + (' If you need more information, ' +
2141 'please run with -h or --help to see valid commands.'))
2142 sys.exit(1)
2143
2144 def find_bots_that_run_test(self, test, bots):
2145 matching_bots = []
2146 for bot in bots:
2147 bot_info = bots[bot]
2148 tests = self.flatten_tests_for_bot(bot_info)
2149 for test_info in tests:
Garrett Beatyffe83c4f2023-09-08 19:07:372150 test_name = test_info['name']
Karen Qiane24b7ee2019-02-12 23:37:062151 if not test_name == test:
2152 continue
2153 matching_bots.append(bot)
2154 return matching_bots
2155
2156 def find_tests_with_params(self, tests, params_dict):
2157 matching_tests = []
2158 for test_name in tests:
2159 test_info = tests[test_name]
2160 if not self.does_test_match(test_info, params_dict):
2161 continue
2162 if not test_name in matching_tests:
2163 matching_tests.append(test_name)
2164 return matching_tests
2165
2166 def flatten_waterfalls_for_query(self, waterfalls):
2167 bots = {}
2168 for waterfall in waterfalls:
Greg Gutermanf60eb052020-03-12 17:40:012169 waterfall_tests = self.generate_output_tests(waterfall)
2170 for bot in waterfall_tests:
2171 bot_info = waterfall_tests[bot]
2172 bots[bot] = bot_info
Karen Qiane24b7ee2019-02-12 23:37:062173 return bots
2174
2175 def flatten_tests_for_bot(self, bot_info):
2176 """Returns a list of flattened tests.
2177
2178 Returns a list of tests not grouped by test category
2179 for a specific bot.
2180 """
2181 TEST_CATS = self.get_test_generator_map().keys()
2182 tests = []
2183 for test_cat in TEST_CATS:
2184 if not test_cat in bot_info:
2185 continue
2186 test_cat_tests = bot_info[test_cat]
2187 tests = tests + test_cat_tests
2188 return tests
2189
2190 def flatten_tests_for_query(self, test_suites):
2191 """Returns a flattened dictionary of tests.
2192
2193 Returns a dictionary of tests associate with their
2194 configuration, not grouped by their test suite.
2195 """
2196 tests = {}
Jamie Madillcf4f8c72021-05-20 19:24:232197 for test_suite in test_suites.values():
Karen Qiane24b7ee2019-02-12 23:37:062198 for test in test_suite:
2199 test_info = test_suite[test]
2200 test_name = test
Karen Qiane24b7ee2019-02-12 23:37:062201 tests[test_name] = test_info
2202 return tests
2203
2204 def parse_query_filter_params(self, params):
2205 """Parses the filter parameters.
2206
2207 Creates a dictionary from the parameters provided
2208 to filter the bot array.
2209 """
2210 params_dict = {}
2211 for p in params:
2212 # flag
2213 if p.startswith("--"):
2214 params_dict[p] = True
2215 else:
2216 pair = p.split(":")
2217 if len(pair) != 2:
2218 self.error_msg('Invalid command.')
2219 # regular parameters
2220 if pair[1].lower() == "true":
2221 params_dict[pair[0]] = True
2222 elif pair[1].lower() == "false":
2223 params_dict[pair[0]] = False
2224 else:
2225 params_dict[pair[0]] = pair[1]
2226 return params_dict
2227
2228 def get_test_suites_dict(self, bots):
2229 """Returns a dictionary of bots and their tests.
2230
2231 Returns a dictionary of bots and a list of their associated tests.
2232 """
2233 test_suite_dict = dict()
2234 for bot in bots:
2235 bot_info = bots[bot]
2236 tests = self.flatten_tests_for_bot(bot_info)
2237 test_suite_dict[bot] = tests
2238 return test_suite_dict
2239
2240 def output_query_result(self, result, json_file=None):
2241 """Outputs the result of the query.
2242
2243 If a json file parameter name is provided, then
2244 the result is output into the json file. If not,
2245 then the result is printed to the console.
2246 """
2247 output = json.dumps(result, indent=2)
2248 if json_file:
2249 self.write_file(json_file, output)
2250 else:
2251 self.print_line(output)
Karen Qiane24b7ee2019-02-12 23:37:062252
Joshua Hood56c673c2022-03-02 20:29:332253 # pylint: disable=inconsistent-return-statements
Karen Qiane24b7ee2019-02-12 23:37:062254 def query(self, args):
2255 """Queries tests or bots.
2256
2257 Depending on the arguments provided, outputs a json of
2258 tests or bots matching the appropriate optional parameters provided.
2259 """
2260 # split up query statement
2261 query = args.query.split('/')
2262 self.load_configuration_files()
2263 self.resolve_configuration_files()
2264
2265 # flatten bots json
2266 tests = self.test_suites
2267 bots = self.flatten_waterfalls_for_query(self.waterfalls)
2268
2269 cmd_class = query[0]
2270
2271 # For queries starting with 'bots'
2272 if cmd_class == "bots":
2273 if len(query) == 1:
2274 return self.output_query_result(bots, args.json)
2275 # query with specific parameters
Joshua Hood56c673c2022-03-02 20:29:332276 if len(query) == 2:
Karen Qiane24b7ee2019-02-12 23:37:062277 if query[1] == 'tests':
2278 test_suites_dict = self.get_test_suites_dict(bots)
2279 return self.output_query_result(test_suites_dict, args.json)
Joshua Hood56c673c2022-03-02 20:29:332280 self.error_msg("This query should be in the format: bots/tests.")
Karen Qiane24b7ee2019-02-12 23:37:062281
2282 else:
2283 self.error_msg("This query should have 0 or 1 '/', found %s instead."
2284 % str(len(query)-1))
2285
2286 # For queries starting with 'bot'
2287 elif cmd_class == "bot":
2288 if not len(query) == 2 and not len(query) == 3:
2289 self.error_msg("Command should have 1 or 2 '/', found %s instead."
2290 % str(len(query)-1))
2291 bot_id = query[1]
2292 if not bot_id in bots:
2293 self.error_msg("No bot named '" + bot_id + "' found.")
2294 bot_info = bots[bot_id]
2295 if len(query) == 2:
2296 return self.output_query_result(bot_info, args.json)
2297 if not query[2] == 'tests':
2298 self.error_msg("The query should be in the format:" +
2299 "bot/<bot-name>/tests.")
2300
2301 bot_tests = self.flatten_tests_for_bot(bot_info)
2302 return self.output_query_result(bot_tests, args.json)
2303
2304 # For queries starting with 'tests'
2305 elif cmd_class == "tests":
2306 if not len(query) == 1 and not len(query) == 2:
2307 self.error_msg("The query should have 0 or 1 '/', found %s instead."
2308 % str(len(query)-1))
2309 flattened_tests = self.flatten_tests_for_query(tests)
2310 if len(query) == 1:
2311 return self.output_query_result(flattened_tests, args.json)
2312
2313 # create params dict
2314 params = query[1].split('&')
2315 params_dict = self.parse_query_filter_params(params)
2316 matching_bots = self.find_tests_with_params(flattened_tests, params_dict)
2317 return self.output_query_result(matching_bots)
2318
2319 # For queries starting with 'test'
2320 elif cmd_class == "test":
2321 if not len(query) == 2 and not len(query) == 3:
2322 self.error_msg("The query should have 1 or 2 '/', found %s instead."
2323 % str(len(query)-1))
2324 test_id = query[1]
2325 if len(query) == 2:
2326 flattened_tests = self.flatten_tests_for_query(tests)
2327 for test in flattened_tests:
2328 if test == test_id:
2329 return self.output_query_result(flattened_tests[test], args.json)
2330 self.error_msg("There is no test named %s." % test_id)
2331 if not query[2] == 'bots':
2332 self.error_msg("The query should be in the format: " +
2333 "test/<test-name>/bots")
2334 bots_for_test = self.find_bots_that_run_test(test_id, bots)
2335 return self.output_query_result(bots_for_test)
2336
2337 else:
2338 self.error_msg("Your command did not match any valid commands." +
2339 "Try starting with 'bots', 'bot', 'tests', or 'test'.")
Joshua Hood56c673c2022-03-02 20:29:332340 # pylint: enable=inconsistent-return-statements
Kenneth Russelleb60cbd22017-12-05 07:54:282341
Garrett Beaty1afaccc2020-06-25 19:58:152342 def main(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:282343 if self.args.check:
Stephen Martinis7eb8b612018-09-21 00:17:502344 self.check_consistency(verbose=self.args.verbose)
Karen Qiane24b7ee2019-02-12 23:37:062345 elif self.args.query:
2346 self.query(self.args)
Kenneth Russelleb60cbd22017-12-05 07:54:282347 else:
Greg Gutermanf60eb052020-03-12 17:40:012348 self.write_json_result(self.generate_outputs())
Kenneth Russelleb60cbd22017-12-05 07:54:282349 return 0
2350
2351if __name__ == "__main__": # pragma: no cover
Garrett Beaty1afaccc2020-06-25 19:58:152352 generator = BBJSONGenerator(BBJSONGenerator.parse_args(sys.argv[1:]))
2353 sys.exit(generator.main())