blob: eaee3ac9230865427c4fe4995e44f9d10f72089e [file] [log] [blame]
Kenneth Russelleb60cbd22017-12-05 07:54:281#!/usr/bin/env python
2# Copyright 2016 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6"""Script to generate the majority of the JSON files in the src/testing/buildbot
7directory. Maintaining these files by hand is too unwieldy.
8"""
9
10import argparse
11import ast
12import collections
13import copy
John Budorick826d5ed2017-12-28 19:27:3214import difflib
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
Greg Gutermanf60eb052020-03-12 17:40:0119import re
Kenneth Russelleb60cbd22017-12-05 07:54:2820import string
21import sys
John Budorick826d5ed2017-12-28 19:27:3222import traceback
Kenneth Russelleb60cbd22017-12-05 07:54:2823
Brian Sheedya31578e2020-05-18 20:24:3624import buildbot_json_magic_substitutions as magic_substitutions
25
Kenneth Russelleb60cbd22017-12-05 07:54:2826THIS_DIR = os.path.dirname(os.path.abspath(__file__))
27
28
29class BBGenErr(Exception):
Nico Weber79dc5f6852018-07-13 19:38:4930 def __init__(self, message):
31 super(BBGenErr, self).__init__(message)
Kenneth Russelleb60cbd22017-12-05 07:54:2832
33
Kenneth Russell8ceeabf2017-12-11 17:53:2834# This class is only present to accommodate certain machines on
35# chromium.android.fyi which run certain tests as instrumentation
36# tests, but not as gtests. If this discrepancy were fixed then the
37# notion could be removed.
38class TestSuiteTypes(object):
39 GTEST = 'gtest'
40
41
Kenneth Russelleb60cbd22017-12-05 07:54:2842class BaseGenerator(object):
43 def __init__(self, bb_gen):
44 self.bb_gen = bb_gen
45
Kenneth Russell8ceeabf2017-12-11 17:53:2846 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:2847 raise NotImplementedError()
48
49 def sort(self, tests):
50 raise NotImplementedError()
51
52
Kenneth Russell8ceeabf2017-12-11 17:53:2853def cmp_tests(a, b):
54 # Prefer to compare based on the "test" key.
55 val = cmp(a['test'], b['test'])
56 if val != 0:
57 return val
58 if 'name' in a and 'name' in b:
59 return cmp(a['name'], b['name']) # pragma: no cover
60 if 'name' not in a and 'name' not in b:
61 return 0 # pragma: no cover
62 # Prefer to put variants of the same test after the first one.
63 if 'name' in a:
64 return 1
65 # 'name' is in b.
66 return -1 # pragma: no cover
67
68
Kenneth Russell8a386d42018-06-02 09:48:0169class GPUTelemetryTestGenerator(BaseGenerator):
Bo Liu555a0f92019-03-29 12:11:5670
71 def __init__(self, bb_gen, is_android_webview=False):
Kenneth Russell8a386d42018-06-02 09:48:0172 super(GPUTelemetryTestGenerator, self).__init__(bb_gen)
Bo Liu555a0f92019-03-29 12:11:5673 self._is_android_webview = is_android_webview
Kenneth Russell8a386d42018-06-02 09:48:0174
75 def generate(self, waterfall, tester_name, tester_config, input_tests):
76 isolated_scripts = []
77 for test_name, test_config in sorted(input_tests.iteritems()):
78 test = self.bb_gen.generate_gpu_telemetry_test(
Bo Liu555a0f92019-03-29 12:11:5679 waterfall, tester_name, tester_config, test_name, test_config,
80 self._is_android_webview)
Kenneth Russell8a386d42018-06-02 09:48:0181 if test:
82 isolated_scripts.append(test)
83 return isolated_scripts
84
85 def sort(self, tests):
86 return sorted(tests, key=lambda x: x['name'])
87
88
Kenneth Russelleb60cbd22017-12-05 07:54:2889class GTestGenerator(BaseGenerator):
90 def __init__(self, bb_gen):
91 super(GTestGenerator, self).__init__(bb_gen)
92
Kenneth Russell8ceeabf2017-12-11 17:53:2893 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:2894 # The relative ordering of some of the tests is important to
95 # minimize differences compared to the handwritten JSON files, since
96 # Python's sorts are stable and there are some tests with the same
97 # key (see gles2_conform_d3d9_test and similar variants). Avoid
98 # losing the order by avoiding coalescing the dictionaries into one.
99 gtests = []
100 for test_name, test_config in sorted(input_tests.iteritems()):
Jeff Yoon67c3e832020-02-08 07:39:38101 # Variants allow more than one definition for a given test, and is defined
102 # in array format from resolve_variants().
103 if not isinstance(test_config, list):
104 test_config = [test_config]
105
106 for config in test_config:
107 test = self.bb_gen.generate_gtest(
108 waterfall, tester_name, tester_config, test_name, config)
109 if test:
110 # generate_gtest may veto the test generation on this tester.
111 gtests.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28112 return gtests
113
114 def sort(self, tests):
Kenneth Russell8ceeabf2017-12-11 17:53:28115 return sorted(tests, cmp=cmp_tests)
Kenneth Russelleb60cbd22017-12-05 07:54:28116
117
118class IsolatedScriptTestGenerator(BaseGenerator):
119 def __init__(self, bb_gen):
120 super(IsolatedScriptTestGenerator, self).__init__(bb_gen)
121
Kenneth Russell8ceeabf2017-12-11 17:53:28122 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28123 isolated_scripts = []
124 for test_name, test_config in sorted(input_tests.iteritems()):
Jeff Yoonb8bfdbf32020-03-13 19:14:43125 # Variants allow more than one definition for a given test, and is defined
126 # in array format from resolve_variants().
127 if not isinstance(test_config, list):
128 test_config = [test_config]
129
130 for config in test_config:
131 test = self.bb_gen.generate_isolated_script_test(
132 waterfall, tester_name, tester_config, test_name, config)
133 if test:
134 isolated_scripts.append(test)
Kenneth Russelleb60cbd22017-12-05 07:54:28135 return isolated_scripts
136
137 def sort(self, tests):
138 return sorted(tests, key=lambda x: x['name'])
139
140
141class ScriptGenerator(BaseGenerator):
142 def __init__(self, bb_gen):
143 super(ScriptGenerator, self).__init__(bb_gen)
144
Kenneth Russell8ceeabf2017-12-11 17:53:28145 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28146 scripts = []
147 for test_name, test_config in sorted(input_tests.iteritems()):
148 test = self.bb_gen.generate_script_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28149 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28150 if test:
151 scripts.append(test)
152 return scripts
153
154 def sort(self, tests):
155 return sorted(tests, key=lambda x: x['name'])
156
157
158class JUnitGenerator(BaseGenerator):
159 def __init__(self, bb_gen):
160 super(JUnitGenerator, self).__init__(bb_gen)
161
Kenneth Russell8ceeabf2017-12-11 17:53:28162 def generate(self, waterfall, tester_name, tester_config, input_tests):
Kenneth Russelleb60cbd22017-12-05 07:54:28163 scripts = []
164 for test_name, test_config in sorted(input_tests.iteritems()):
165 test = self.bb_gen.generate_junit_test(
Kenneth Russell8ceeabf2017-12-11 17:53:28166 waterfall, tester_name, tester_config, test_name, test_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28167 if test:
168 scripts.append(test)
169 return scripts
170
171 def sort(self, tests):
172 return sorted(tests, key=lambda x: x['test'])
173
174
Jeff Yoon67c3e832020-02-08 07:39:38175def check_compound_references(other_test_suites=None,
176 sub_suite=None,
177 suite=None,
178 target_test_suites=None,
179 test_type=None,
180 **kwargs):
181 """Ensure comound reference's don't target other compounds"""
182 del kwargs
183 if sub_suite in other_test_suites or sub_suite in target_test_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15184 raise BBGenErr('%s may not refer to other composition type test '
185 'suites (error found while processing %s)' %
186 (test_type, suite))
187
Jeff Yoon67c3e832020-02-08 07:39:38188
189def check_basic_references(basic_suites=None,
190 sub_suite=None,
191 suite=None,
192 **kwargs):
193 """Ensure test has a basic suite reference"""
194 del kwargs
195 if sub_suite not in basic_suites:
Garrett Beaty1afaccc2020-06-25 19:58:15196 raise BBGenErr('Unable to find reference to %s while processing %s' %
197 (sub_suite, suite))
198
Jeff Yoon67c3e832020-02-08 07:39:38199
200def check_conflicting_definitions(basic_suites=None,
201 seen_tests=None,
202 sub_suite=None,
203 suite=None,
204 test_type=None,
205 **kwargs):
206 """Ensure that if a test is reachable via multiple basic suites,
207 all of them have an identical definition of the tests.
208 """
209 del kwargs
210 for test_name in basic_suites[sub_suite]:
211 if (test_name in seen_tests and
212 basic_suites[sub_suite][test_name] !=
213 basic_suites[seen_tests[test_name]][test_name]):
214 raise BBGenErr('Conflicting test definitions for %s from %s '
215 'and %s in %s (error found while processing %s)'
216 % (test_name, seen_tests[test_name], sub_suite,
217 test_type, suite))
218 seen_tests[test_name] = sub_suite
219
220def check_matrix_identifier(sub_suite=None,
221 suite=None,
222 suite_def=None,
Jeff Yoonda581c32020-03-06 03:56:05223 all_variants=None,
Jeff Yoon67c3e832020-02-08 07:39:38224 **kwargs):
225 """Ensure 'idenfitier' is defined for each variant"""
226 del kwargs
227 sub_suite_config = suite_def[sub_suite]
228 for variant in sub_suite_config.get('variants', []):
Jeff Yoonda581c32020-03-06 03:56:05229 if isinstance(variant, str):
230 if variant not in all_variants:
231 raise BBGenErr('Missing variant definition for %s in variants.pyl'
232 % variant)
233 variant = all_variants[variant]
234
Jeff Yoon67c3e832020-02-08 07:39:38235 if not 'identifier' in variant:
236 raise BBGenErr('Missing required identifier field in matrix '
237 'compound suite %s, %s' % (suite, sub_suite))
238
239
Kenneth Russelleb60cbd22017-12-05 07:54:28240class BBJSONGenerator(object):
Garrett Beaty1afaccc2020-06-25 19:58:15241 def __init__(self, args):
Kenneth Russelleb60cbd22017-12-05 07:54:28242 self.this_dir = THIS_DIR
Garrett Beaty1afaccc2020-06-25 19:58:15243 self.args = args
Kenneth Russelleb60cbd22017-12-05 07:54:28244 self.waterfalls = None
245 self.test_suites = None
246 self.exceptions = None
Stephen Martinisb72f6d22018-10-04 23:29:01247 self.mixins = None
Nodir Turakulovfce34292019-12-18 17:05:41248 self.gn_isolate_map = None
Jeff Yoonda581c32020-03-06 03:56:05249 self.variants = None
Kenneth Russelleb60cbd22017-12-05 07:54:28250
Garrett Beaty1afaccc2020-06-25 19:58:15251 @staticmethod
252 def parse_args(argv):
253
254 # RawTextHelpFormatter allows for styling of help statement
255 parser = argparse.ArgumentParser(
256 formatter_class=argparse.RawTextHelpFormatter)
257
258 group = parser.add_mutually_exclusive_group()
259 group.add_argument(
260 '-c',
261 '--check',
262 action='store_true',
263 help=
264 'Do consistency checks of configuration and generated files and then '
265 'exit. Used during presubmit. '
266 'Causes the tool to not generate any files.')
267 group.add_argument(
268 '--query',
269 type=str,
270 help=(
271 "Returns raw JSON information of buildbots and tests.\n" +
272 "Examples:\n" + " List all bots (all info):\n" +
273 " --query bots\n\n" +
274 " List all bots and only their associated tests:\n" +
275 " --query bots/tests\n\n" +
276 " List all information about 'bot1' " +
277 "(make sure you have quotes):\n" + " --query bot/'bot1'\n\n" +
278 " List tests running for 'bot1' (make sure you have quotes):\n" +
279 " --query bot/'bot1'/tests\n\n" + " List all tests:\n" +
280 " --query tests\n\n" +
281 " List all tests and the bots running them:\n" +
282 " --query tests/bots\n\n" +
283 " List all tests that satisfy multiple parameters\n" +
284 " (separation of parameters by '&' symbol):\n" +
285 " --query tests/'device_os:Android&device_type:hammerhead'\n\n" +
286 " List all tests that run with a specific flag:\n" +
287 " --query bots/'--test-launcher-print-test-studio=always'\n\n" +
288 " List specific test (make sure you have quotes):\n"
289 " --query test/'test1'\n\n"
290 " List all bots running 'test1' " +
291 "(make sure you have quotes):\n" + " --query test/'test1'/bots"))
292 parser.add_argument(
293 '-n',
294 '--new-files',
295 action='store_true',
296 help=
297 'Write output files as .new.json. Useful during development so old and '
298 'new files can be looked at side-by-side.')
299 parser.add_argument('-v',
300 '--verbose',
301 action='store_true',
302 help='Increases verbosity. Affects consistency checks.')
303 parser.add_argument('waterfall_filters',
304 metavar='waterfalls',
305 type=str,
306 nargs='*',
307 help='Optional list of waterfalls to generate.')
308 parser.add_argument(
309 '--pyl-files-dir',
310 type=os.path.realpath,
311 help='Path to the directory containing the input .pyl files.')
312 parser.add_argument(
313 '--json',
314 metavar='JSON_FILE_PATH',
315 help='Outputs results into a json file. Only works with query function.'
316 )
317 parser.add_argument(
318 '--infra-config-dir',
319 help='Path to the LUCI services configuration directory',
320 default=os.path.abspath(
321 os.path.join(os.path.dirname(__file__), '..', '..', 'infra',
322 'config')))
323 args = parser.parse_args(argv)
324 if args.json and not args.query:
325 parser.error(
326 "The --json flag can only be used with --query.") # pragma: no cover
327 args.infra_config_dir = os.path.abspath(args.infra_config_dir)
328 return args
329
Kenneth Russelleb60cbd22017-12-05 07:54:28330 def generate_abs_file_path(self, relative_path):
Garrett Beaty1afaccc2020-06-25 19:58:15331 return os.path.join(self.this_dir, relative_path)
Kenneth Russelleb60cbd22017-12-05 07:54:28332
Stephen Martinis7eb8b612018-09-21 00:17:50333 def print_line(self, line):
334 # Exists so that tests can mock
335 print line # pragma: no cover
336
Kenneth Russelleb60cbd22017-12-05 07:54:28337 def read_file(self, relative_path):
Garrett Beaty1afaccc2020-06-25 19:58:15338 with open(self.generate_abs_file_path(relative_path)) as fp:
339 return fp.read()
Kenneth Russelleb60cbd22017-12-05 07:54:28340
341 def write_file(self, relative_path, contents):
Garrett Beaty1afaccc2020-06-25 19:58:15342 with open(self.generate_abs_file_path(relative_path), 'wb') as fp:
343 fp.write(contents)
Kenneth Russelleb60cbd22017-12-05 07:54:28344
Zhiling Huangbe008172018-03-08 19:13:11345 def pyl_file_path(self, filename):
346 if self.args and self.args.pyl_files_dir:
347 return os.path.join(self.args.pyl_files_dir, filename)
348 return filename
349
Kenneth Russelleb60cbd22017-12-05 07:54:28350 def load_pyl_file(self, filename):
351 try:
Zhiling Huangbe008172018-03-08 19:13:11352 return ast.literal_eval(self.read_file(
353 self.pyl_file_path(filename)))
Kenneth Russelleb60cbd22017-12-05 07:54:28354 except (SyntaxError, ValueError) as e: # pragma: no cover
355 raise BBGenErr('Failed to parse pyl file "%s": %s' %
356 (filename, e)) # pragma: no cover
357
Kenneth Russell8a386d42018-06-02 09:48:01358 # TOOD(kbr): require that os_type be specified for all bots in waterfalls.pyl.
359 # Currently it is only mandatory for bots which run GPU tests. Change these to
360 # use [] instead of .get().
Kenneth Russelleb60cbd22017-12-05 07:54:28361 def is_android(self, tester_config):
362 return tester_config.get('os_type') == 'android'
363
Ben Pastenea9e583b2019-01-16 02:57:26364 def is_chromeos(self, tester_config):
365 return tester_config.get('os_type') == 'chromeos'
366
Kenneth Russell8a386d42018-06-02 09:48:01367 def is_linux(self, tester_config):
368 return tester_config.get('os_type') == 'linux'
369
Kai Ninomiya40de9f52019-10-18 21:38:49370 def is_mac(self, tester_config):
371 return tester_config.get('os_type') == 'mac'
372
373 def is_win(self, tester_config):
374 return tester_config.get('os_type') == 'win'
375
376 def is_win64(self, tester_config):
377 return (tester_config.get('os_type') == 'win' and
378 tester_config.get('browser_config') == 'release_x64')
379
Kenneth Russelleb60cbd22017-12-05 07:54:28380 def get_exception_for_test(self, test_name, test_config):
381 # gtests may have both "test" and "name" fields, and usually, if the "name"
382 # field is specified, it means that the same test is being repurposed
383 # multiple times with different command line arguments. To handle this case,
384 # prefer to lookup per the "name" field of the test itself, as opposed to
385 # the "test_name", which is actually the "test" field.
386 if 'name' in test_config:
387 return self.exceptions.get(test_config['name'])
388 else:
389 return self.exceptions.get(test_name)
390
Nico Weberb0b3f5862018-07-13 18:45:15391 def should_run_on_tester(self, waterfall, tester_name,test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28392 # Currently, the only reason a test should not run on a given tester is that
393 # it's in the exceptions. (Once the GPU waterfall generation script is
394 # incorporated here, the rules will become more complex.)
395 exception = self.get_exception_for_test(test_name, test_config)
396 if not exception:
397 return True
Kenneth Russell8ceeabf2017-12-11 17:53:28398 remove_from = None
Kenneth Russelleb60cbd22017-12-05 07:54:28399 remove_from = exception.get('remove_from')
Kenneth Russell8ceeabf2017-12-11 17:53:28400 if remove_from:
401 if tester_name in remove_from:
402 return False
403 # TODO(kbr): this code path was added for some tests (including
404 # android_webview_unittests) on one machine (Nougat Phone
405 # Tester) which exists with the same name on two waterfalls,
406 # chromium.android and chromium.fyi; the tests are run on one
407 # but not the other. Once the bots are all uniquely named (a
408 # different ongoing project) this code should be removed.
409 # TODO(kbr): add coverage.
410 return (tester_name + ' ' + waterfall['name']
411 not in remove_from) # pragma: no cover
412 return True
Kenneth Russelleb60cbd22017-12-05 07:54:28413
Nico Weber79dc5f6852018-07-13 19:38:49414 def get_test_modifications(self, test, test_name, tester_name):
Kenneth Russelleb60cbd22017-12-05 07:54:28415 exception = self.get_exception_for_test(test_name, test)
416 if not exception:
417 return None
Nico Weber79dc5f6852018-07-13 19:38:49418 return exception.get('modifications', {}).get(tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28419
Brian Sheedye6ea0ee2019-07-11 02:54:37420 def get_test_replacements(self, test, test_name, tester_name):
421 exception = self.get_exception_for_test(test_name, test)
422 if not exception:
423 return None
424 return exception.get('replacements', {}).get(tester_name)
425
Kenneth Russell8a386d42018-06-02 09:48:01426 def merge_command_line_args(self, arr, prefix, splitter):
427 prefix_len = len(prefix)
Kenneth Russell650995a2018-05-03 21:17:01428 idx = 0
429 first_idx = -1
Kenneth Russell8a386d42018-06-02 09:48:01430 accumulated_args = []
Kenneth Russell650995a2018-05-03 21:17:01431 while idx < len(arr):
432 flag = arr[idx]
433 delete_current_entry = False
Kenneth Russell8a386d42018-06-02 09:48:01434 if flag.startswith(prefix):
435 arg = flag[prefix_len:]
436 accumulated_args.extend(arg.split(splitter))
Kenneth Russell650995a2018-05-03 21:17:01437 if first_idx < 0:
438 first_idx = idx
439 else:
440 delete_current_entry = True
441 if delete_current_entry:
442 del arr[idx]
443 else:
444 idx += 1
445 if first_idx >= 0:
Kenneth Russell8a386d42018-06-02 09:48:01446 arr[first_idx] = prefix + splitter.join(accumulated_args)
447 return arr
448
449 def maybe_fixup_args_array(self, arr):
450 # The incoming array of strings may be an array of command line
451 # arguments. To make it easier to turn on certain features per-bot or
452 # per-test-suite, look specifically for certain flags and merge them
453 # appropriately.
454 # --enable-features=Feature1 --enable-features=Feature2
455 # are merged to:
456 # --enable-features=Feature1,Feature2
457 # and:
458 # --extra-browser-args=arg1 --extra-browser-args=arg2
459 # are merged to:
460 # --extra-browser-args=arg1 arg2
461 arr = self.merge_command_line_args(arr, '--enable-features=', ',')
462 arr = self.merge_command_line_args(arr, '--extra-browser-args=', ' ')
Kenneth Russell650995a2018-05-03 21:17:01463 return arr
464
Brian Sheedya31578e2020-05-18 20:24:36465 def substitute_magic_args(self, test_config):
466 """Substitutes any magic substitution args present in |test_config|.
467
468 Substitutions are done in-place.
469
470 See buildbot_json_magic_substitutions.py for more information on this
471 feature.
472
473 Args:
474 test_config: A dict containing a configuration for a specific test on
475 a specific builder, e.g. the output of update_and_cleanup_test.
476 """
477 substituted_array = []
478 for arg in test_config.get('args', []):
479 if arg.startswith(magic_substitutions.MAGIC_SUBSTITUTION_PREFIX):
480 function = arg.replace(
481 magic_substitutions.MAGIC_SUBSTITUTION_PREFIX, '')
482 if hasattr(magic_substitutions, function):
483 substituted_array.extend(
484 getattr(magic_substitutions, function)(test_config))
485 else:
486 raise BBGenErr(
487 'Magic substitution function %s does not exist' % function)
488 else:
489 substituted_array.append(arg)
490 if substituted_array:
491 test_config['args'] = self.maybe_fixup_args_array(substituted_array)
492
Kenneth Russelleb60cbd22017-12-05 07:54:28493 def dictionary_merge(self, a, b, path=None, update=True):
494 """http://stackoverflow.com/questions/7204805/
495 python-dictionaries-of-dictionaries-merge
496 merges b into a
497 """
498 if path is None:
499 path = []
500 for key in b:
501 if key in a:
502 if isinstance(a[key], dict) and isinstance(b[key], dict):
503 self.dictionary_merge(a[key], b[key], path + [str(key)])
504 elif a[key] == b[key]:
505 pass # same leaf value
506 elif isinstance(a[key], list) and isinstance(b[key], list):
Stephen Martinis3bed2ab2018-04-23 19:42:06507 # Args arrays are lists of strings. Just concatenate them,
508 # and don't sort them, in order to keep some needed
509 # arguments adjacent (like --time-out-ms [arg], etc.)
Kenneth Russell8ceeabf2017-12-11 17:53:28510 if all(isinstance(x, str)
511 for x in itertools.chain(a[key], b[key])):
Kenneth Russell650995a2018-05-03 21:17:01512 a[key] = self.maybe_fixup_args_array(a[key] + b[key])
Kenneth Russell8ceeabf2017-12-11 17:53:28513 else:
514 # TODO(kbr): this only works properly if the two arrays are
515 # the same length, which is currently always the case in the
516 # swarming dimension_sets that we have to merge. It will fail
517 # to merge / override 'args' arrays which are different
518 # length.
519 for idx in xrange(len(b[key])):
520 try:
521 a[key][idx] = self.dictionary_merge(a[key][idx], b[key][idx],
522 path + [str(key), str(idx)],
523 update=update)
Jeff Yoon8154e582019-12-03 23:30:01524 except (IndexError, TypeError):
525 raise BBGenErr('Error merging lists by key "%s" from source %s '
526 'into target %s at index %s. Verify target list '
527 'length is equal or greater than source'
528 % (str(key), str(b), str(a), str(idx)))
John Budorick5bc387fe2019-05-09 20:02:53529 elif update:
530 if b[key] is None:
531 del a[key]
532 else:
533 a[key] = b[key]
Kenneth Russelleb60cbd22017-12-05 07:54:28534 else:
535 raise BBGenErr('Conflict at %s' % '.'.join(
536 path + [str(key)])) # pragma: no cover
John Budorick5bc387fe2019-05-09 20:02:53537 elif b[key] is not None:
Kenneth Russelleb60cbd22017-12-05 07:54:28538 a[key] = b[key]
539 return a
540
John Budorickab108712018-09-01 00:12:21541 def initialize_args_for_test(
542 self, generated_test, tester_config, additional_arg_keys=None):
John Budorickab108712018-09-01 00:12:21543 args = []
544 args.extend(generated_test.get('args', []))
545 args.extend(tester_config.get('args', []))
John Budorickedfe7f872018-01-23 15:27:22546
Kenneth Russell8a386d42018-06-02 09:48:01547 def add_conditional_args(key, fn):
John Budorickab108712018-09-01 00:12:21548 val = generated_test.pop(key, [])
549 if fn(tester_config):
550 args.extend(val)
Kenneth Russell8a386d42018-06-02 09:48:01551
552 add_conditional_args('desktop_args', lambda cfg: not self.is_android(cfg))
553 add_conditional_args('linux_args', self.is_linux)
554 add_conditional_args('android_args', self.is_android)
Ben Pastene52890ace2019-05-24 20:03:36555 add_conditional_args('chromeos_args', self.is_chromeos)
Kai Ninomiya40de9f52019-10-18 21:38:49556 add_conditional_args('mac_args', self.is_mac)
557 add_conditional_args('win_args', self.is_win)
558 add_conditional_args('win64_args', self.is_win64)
Kenneth Russell8a386d42018-06-02 09:48:01559
John Budorickab108712018-09-01 00:12:21560 for key in additional_arg_keys or []:
561 args.extend(generated_test.pop(key, []))
562 args.extend(tester_config.get(key, []))
563
564 if args:
565 generated_test['args'] = self.maybe_fixup_args_array(args)
Kenneth Russell8a386d42018-06-02 09:48:01566
Kenneth Russelleb60cbd22017-12-05 07:54:28567 def initialize_swarming_dictionary_for_test(self, generated_test,
568 tester_config):
569 if 'swarming' not in generated_test:
570 generated_test['swarming'] = {}
Dirk Pranke81ff51c2017-12-09 19:24:28571 if not 'can_use_on_swarming_builders' in generated_test['swarming']:
572 generated_test['swarming'].update({
Jeff Yoon67c3e832020-02-08 07:39:38573 'can_use_on_swarming_builders': tester_config.get('use_swarming',
574 True)
Dirk Pranke81ff51c2017-12-09 19:24:28575 })
Kenneth Russelleb60cbd22017-12-05 07:54:28576 if 'swarming' in tester_config:
Ben Pastene796c62862018-06-13 02:40:03577 if ('dimension_sets' not in generated_test['swarming'] and
578 'dimension_sets' in tester_config['swarming']):
Kenneth Russelleb60cbd22017-12-05 07:54:28579 generated_test['swarming']['dimension_sets'] = copy.deepcopy(
580 tester_config['swarming']['dimension_sets'])
581 self.dictionary_merge(generated_test['swarming'],
582 tester_config['swarming'])
583 # Apply any Android-specific Swarming dimensions after the generic ones.
584 if 'android_swarming' in generated_test:
585 if self.is_android(tester_config): # pragma: no cover
586 self.dictionary_merge(
587 generated_test['swarming'],
588 generated_test['android_swarming']) # pragma: no cover
589 del generated_test['android_swarming'] # pragma: no cover
590
591 def clean_swarming_dictionary(self, swarming_dict):
592 # Clean out redundant entries from a test's "swarming" dictionary.
593 # This is really only needed to retain 100% parity with the
594 # handwritten JSON files, and can be removed once all the files are
595 # autogenerated.
596 if 'shards' in swarming_dict:
597 if swarming_dict['shards'] == 1: # pragma: no cover
598 del swarming_dict['shards'] # pragma: no cover
Kenneth Russellfbda3c532017-12-08 23:57:24599 if 'hard_timeout' in swarming_dict:
600 if swarming_dict['hard_timeout'] == 0: # pragma: no cover
601 del swarming_dict['hard_timeout'] # pragma: no cover
Stephen Martinisf5f4ea22018-09-20 01:07:43602 if not swarming_dict.get('can_use_on_swarming_builders', False):
Kenneth Russelleb60cbd22017-12-05 07:54:28603 # Remove all other keys.
604 for k in swarming_dict.keys(): # pragma: no cover
605 if k != 'can_use_on_swarming_builders': # pragma: no cover
606 del swarming_dict[k] # pragma: no cover
607
Stephen Martinis0382bc12018-09-17 22:29:07608 def update_and_cleanup_test(self, test, test_name, tester_name, tester_config,
609 waterfall):
610 # Apply swarming mixins.
Stephen Martinisb72f6d22018-10-04 23:29:01611 test = self.apply_all_mixins(
Stephen Martinis0382bc12018-09-17 22:29:07612 test, waterfall, tester_name, tester_config)
Kenneth Russelleb60cbd22017-12-05 07:54:28613 # See if there are any exceptions that need to be merged into this
614 # test's specification.
Nico Weber79dc5f6852018-07-13 19:38:49615 modifications = self.get_test_modifications(test, test_name, tester_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28616 if modifications:
617 test = self.dictionary_merge(test, modifications)
Dirk Pranke1b767092017-12-07 04:44:23618 if 'swarming' in test:
619 self.clean_swarming_dictionary(test['swarming'])
Ben Pastenee012aea42019-05-14 22:32:28620 # Ensure all Android Swarming tests run only on userdebug builds if another
621 # build type was not specified.
622 if 'swarming' in test and self.is_android(tester_config):
623 for d in test['swarming'].get('dimension_sets', []):
Ben Pastened15aa8a2019-05-16 16:59:22624 if d.get('os') == 'Android' and not d.get('device_os_type'):
Ben Pastenee012aea42019-05-14 22:32:28625 d['device_os_type'] = 'userdebug'
Brian Sheedye6ea0ee2019-07-11 02:54:37626 self.replace_test_args(test, test_name, tester_name)
Ben Pastenee012aea42019-05-14 22:32:28627
Kenneth Russelleb60cbd22017-12-05 07:54:28628 return test
629
Brian Sheedye6ea0ee2019-07-11 02:54:37630 def replace_test_args(self, test, test_name, tester_name):
631 replacements = self.get_test_replacements(
632 test, test_name, tester_name) or {}
633 valid_replacement_keys = ['args', 'non_precommit_args', 'precommit_args']
634 for key, replacement_dict in replacements.iteritems():
635 if key not in valid_replacement_keys:
636 raise BBGenErr(
637 'Given replacement key %s for %s on %s is not in the list of valid '
638 'keys %s' % (key, test_name, tester_name, valid_replacement_keys))
639 for replacement_key, replacement_val in replacement_dict.iteritems():
640 found_key = False
641 for i, test_key in enumerate(test.get(key, [])):
642 # Handle both the key/value being replaced being defined as two
643 # separate items or as key=value.
644 if test_key == replacement_key:
645 found_key = True
646 # Handle flags without values.
647 if replacement_val == None:
648 del test[key][i]
649 else:
650 test[key][i+1] = replacement_val
651 break
652 elif test_key.startswith(replacement_key + '='):
653 found_key = True
654 if replacement_val == None:
655 del test[key][i]
656 else:
657 test[key][i] = '%s=%s' % (replacement_key, replacement_val)
658 break
659 if not found_key:
660 raise BBGenErr('Could not find %s in existing list of values for key '
661 '%s in %s on %s' % (replacement_key, key, test_name,
662 tester_name))
663
Shenghua Zhangaba8bad2018-02-07 02:12:09664 def add_common_test_properties(self, test, tester_config):
Brian Sheedy5ea8f6c62020-05-21 03:05:05665 if self.is_chromeos(tester_config) and tester_config.get('use_swarming',
Ben Pastenea9e583b2019-01-16 02:57:26666 True):
667 # The presence of the "device_type" dimension indicates that the tests
Brian Sheedy9493da892020-05-13 22:58:06668 # are targeting CrOS hardware and so need the special trigger script.
669 dimension_sets = test['swarming']['dimension_sets']
Ben Pastenea9e583b2019-01-16 02:57:26670 if all('device_type' in ds for ds in dimension_sets):
671 test['trigger_script'] = {
672 'script': '//testing/trigger_scripts/chromeos_device_trigger.py',
673 }
Shenghua Zhangaba8bad2018-02-07 02:12:09674
Ben Pastene858f4be2019-01-09 23:52:09675 def add_android_presentation_args(self, tester_config, test_name, result):
676 args = result.get('args', [])
John Budorick262ae112019-07-12 19:24:38677 bucket = tester_config.get('results_bucket', 'chromium-result-details')
678 args.append('--gs-results-bucket=%s' % bucket)
Ben Pastene858f4be2019-01-09 23:52:09679 if (result['swarming']['can_use_on_swarming_builders'] and not
680 tester_config.get('skip_merge_script', False)):
681 result['merge'] = {
682 'args': [
683 '--bucket',
John Budorick262ae112019-07-12 19:24:38684 bucket,
Ben Pastene858f4be2019-01-09 23:52:09685 '--test-name',
Rakib M. Hasanc9e01c62020-07-27 22:48:12686 result.get('name', test_name)
Ben Pastene858f4be2019-01-09 23:52:09687 ],
688 'script': '//build/android/pylib/results/presentation/'
689 'test_results_presentation.py',
690 }
691 if not tester_config.get('skip_cipd_packages', False):
Ben Pastenee5949ea82019-01-10 21:45:26692 cipd_packages = result['swarming'].get('cipd_packages', [])
693 cipd_packages.append(
Ben Pastene858f4be2019-01-09 23:52:09694 {
695 'cipd_package': 'infra/tools/luci/logdog/butler/${platform}',
696 'location': 'bin',
697 'revision': 'git_revision:ff387eadf445b24c935f1cf7d6ddd279f8a6b04c',
698 }
Ben Pastenee5949ea82019-01-10 21:45:26699 )
700 result['swarming']['cipd_packages'] = cipd_packages
Ben Pastene858f4be2019-01-09 23:52:09701 if not tester_config.get('skip_output_links', False):
702 result['swarming']['output_links'] = [
703 {
704 'link': [
705 'https://luci-logdog.appspot.com/v/?s',
706 '=android%2Fswarming%2Flogcats%2F',
707 '${TASK_ID}%2F%2B%2Funified_logcats',
708 ],
709 'name': 'shard #${SHARD_INDEX} logcats',
710 },
711 ]
712 if args:
713 result['args'] = args
714
Kenneth Russelleb60cbd22017-12-05 07:54:28715 def generate_gtest(self, waterfall, tester_name, tester_config, test_name,
716 test_config):
717 if not self.should_run_on_tester(
Nico Weberb0b3f5862018-07-13 18:45:15718 waterfall, tester_name, test_name, test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28719 return None
720 result = copy.deepcopy(test_config)
721 if 'test' in result:
Rakib M. Hasanc9e01c62020-07-27 22:48:12722 if 'name' not in result:
723 result['name'] = test_name
Kenneth Russelleb60cbd22017-12-05 07:54:28724 else:
725 result['test'] = test_name
726 self.initialize_swarming_dictionary_for_test(result, tester_config)
John Budorickab108712018-09-01 00:12:21727
728 self.initialize_args_for_test(
729 result, tester_config, additional_arg_keys=['gtest_args'])
Kenneth Russelleb60cbd22017-12-05 07:54:28730 if self.is_android(tester_config) and tester_config.get('use_swarming',
731 True):
Ben Pastene858f4be2019-01-09 23:52:09732 self.add_android_presentation_args(tester_config, test_name, result)
733 result['args'] = result.get('args', []) + ['--recover-devices']
Benjamin Pastene766d48f52017-12-18 21:47:42734
Stephen Martinis0382bc12018-09-17 22:29:07735 result = self.update_and_cleanup_test(
736 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09737 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36738 self.substitute_magic_args(result)
Stephen Martinisbc7b7772019-05-01 22:01:43739
740 if not result.get('merge'):
741 # TODO(https://crbug.com/958376): Consider adding the ability to not have
742 # this default.
743 result['merge'] = {
744 'script': '//testing/merge_scripts/standard_gtest_merge.py',
745 'args': [],
746 }
Kenneth Russelleb60cbd22017-12-05 07:54:28747 return result
748
749 def generate_isolated_script_test(self, waterfall, tester_name, tester_config,
750 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01751 if not self.should_run_on_tester(waterfall, tester_name, test_name,
752 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28753 return None
754 result = copy.deepcopy(test_config)
755 result['isolate_name'] = result.get('isolate_name', test_name)
Jeff Yoonb8bfdbf32020-03-13 19:14:43756 result['name'] = result.get('name', test_name)
Kenneth Russelleb60cbd22017-12-05 07:54:28757 self.initialize_swarming_dictionary_for_test(result, tester_config)
Kenneth Russell8a386d42018-06-02 09:48:01758 self.initialize_args_for_test(result, tester_config)
Ben Pastene858f4be2019-01-09 23:52:09759 if tester_config.get('use_android_presentation', False):
760 self.add_android_presentation_args(tester_config, test_name, result)
Stephen Martinis0382bc12018-09-17 22:29:07761 result = self.update_and_cleanup_test(
762 result, test_name, tester_name, tester_config, waterfall)
Shenghua Zhangaba8bad2018-02-07 02:12:09763 self.add_common_test_properties(result, tester_config)
Brian Sheedya31578e2020-05-18 20:24:36764 self.substitute_magic_args(result)
Stephen Martinisf50047062019-05-06 22:26:17765
766 if not result.get('merge'):
767 # TODO(https://crbug.com/958376): Consider adding the ability to not have
768 # this default.
769 result['merge'] = {
770 'script': '//testing/merge_scripts/standard_isolated_script_merge.py',
771 'args': [],
772 }
Kenneth Russelleb60cbd22017-12-05 07:54:28773 return result
774
775 def generate_script_test(self, waterfall, tester_name, tester_config,
776 test_name, test_config):
Brian Sheedy158cd0f2019-04-26 01:12:44777 # TODO(https://crbug.com/953072): Remove this check whenever a better
778 # long-term solution is implemented.
779 if (waterfall.get('forbid_script_tests', False) or
780 waterfall['machines'][tester_name].get('forbid_script_tests', False)):
781 raise BBGenErr('Attempted to generate a script test on tester ' +
782 tester_name + ', which explicitly forbids script tests')
Kenneth Russell8a386d42018-06-02 09:48:01783 if not self.should_run_on_tester(waterfall, tester_name, test_name,
784 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28785 return None
786 result = {
787 'name': test_name,
788 'script': test_config['script']
789 }
Stephen Martinis0382bc12018-09-17 22:29:07790 result = self.update_and_cleanup_test(
791 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36792 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28793 return result
794
795 def generate_junit_test(self, waterfall, tester_name, tester_config,
796 test_name, test_config):
Kenneth Russell8a386d42018-06-02 09:48:01797 if not self.should_run_on_tester(waterfall, tester_name, test_name,
798 test_config):
Kenneth Russelleb60cbd22017-12-05 07:54:28799 return None
John Budorickdef6acb2019-09-17 22:51:09800 result = copy.deepcopy(test_config)
801 result.update({
John Budorickcadc4952019-09-16 23:51:37802 'name': test_name,
803 'test': test_config.get('test', test_name),
John Budorickdef6acb2019-09-17 22:51:09804 })
805 self.initialize_args_for_test(result, tester_config)
806 result = self.update_and_cleanup_test(
807 result, test_name, tester_name, tester_config, waterfall)
Brian Sheedya31578e2020-05-18 20:24:36808 self.substitute_magic_args(result)
Kenneth Russelleb60cbd22017-12-05 07:54:28809 return result
810
Stephen Martinis2a0667022018-09-25 22:31:14811 def substitute_gpu_args(self, tester_config, swarming_config, args):
Kenneth Russell8a386d42018-06-02 09:48:01812 substitutions = {
813 # Any machine in waterfalls.pyl which desires to run GPU tests
814 # must provide the os_type key.
815 'os_type': tester_config['os_type'],
816 'gpu_vendor_id': '0',
817 'gpu_device_id': '0',
818 }
Stephen Martinis2a0667022018-09-25 22:31:14819 dimension_set = swarming_config['dimension_sets'][0]
Kenneth Russell8a386d42018-06-02 09:48:01820 if 'gpu' in dimension_set:
821 # First remove the driver version, then split into vendor and device.
822 gpu = dimension_set['gpu']
Brian Sheedy0e26c4e02020-05-28 22:09:09823 gpu = gpu.split('-')[0].split(':')
Kenneth Russell8a386d42018-06-02 09:48:01824 substitutions['gpu_vendor_id'] = gpu[0]
825 substitutions['gpu_device_id'] = gpu[1]
826 return [string.Template(arg).safe_substitute(substitutions) for arg in args]
827
828 def generate_gpu_telemetry_test(self, waterfall, tester_name, tester_config,
Bo Liu555a0f92019-03-29 12:11:56829 test_name, test_config, is_android_webview):
Kenneth Russell8a386d42018-06-02 09:48:01830 # These are all just specializations of isolated script tests with
831 # a bunch of boilerplate command line arguments added.
832
833 # The step name must end in 'test' or 'tests' in order for the
834 # results to automatically show up on the flakiness dashboard.
835 # (At least, this was true some time ago.) Continue to use this
836 # naming convention for the time being to minimize changes.
837 step_name = test_config.get('name', test_name)
838 if not (step_name.endswith('test') or step_name.endswith('tests')):
839 step_name = '%s_tests' % step_name
840 result = self.generate_isolated_script_test(
841 waterfall, tester_name, tester_config, step_name, test_config)
842 if not result:
843 return None
Chong Gub75754b32020-03-13 16:39:20844 result['isolate_name'] = test_config.get(
845 'isolate_name', 'telemetry_gpu_integration_test')
Chan Liab7d8dd82020-04-24 23:42:19846
Chan Lia3ad1502020-04-28 05:32:11847 # Populate test_id_prefix.
Chan Liab7d8dd82020-04-24 23:42:19848 gn_entry = (
849 self.gn_isolate_map.get(result['isolate_name']) or
850 self.gn_isolate_map.get('telemetry_gpu_integration_test'))
Chan Li17d969f92020-07-10 00:50:03851 result['test_id_prefix'] = 'ninja:%s/' % gn_entry['label']
Chan Liab7d8dd82020-04-24 23:42:19852
Kenneth Russell8a386d42018-06-02 09:48:01853 args = result.get('args', [])
854 test_to_run = result.pop('telemetry_test_name', test_name)
erikchen6da2d9b2018-08-03 23:01:14855
856 # These tests upload and download results from cloud storage and therefore
857 # aren't idempotent yet. https://crbug.com/549140.
858 result['swarming']['idempotent'] = False
859
Kenneth Russell44910c32018-12-03 23:35:11860 # The GPU tests act much like integration tests for the entire browser, and
861 # tend to uncover flakiness bugs more readily than other test suites. In
862 # order to surface any flakiness more readily to the developer of the CL
863 # which is introducing it, we disable retries with patch on the commit
864 # queue.
865 result['should_retry_with_patch'] = False
866
Bo Liu555a0f92019-03-29 12:11:56867 browser = ('android-webview-instrumentation'
868 if is_android_webview else tester_config['browser_config'])
Brian Sheedy4053a702020-07-28 02:09:52869
870 # Most platforms require --enable-logging=stderr to get useful browser logs.
871 # However, this actively messes with logging on CrOS (because Chrome's
872 # stderr goes nowhere on CrOS) AND --log-level=0 is required for some reason
873 # in order to see JavaScript console messages. See
874 # https://chromium.googlesource.com/chromium/src.git/+/HEAD/docs/chrome_os_logging.md
875 logging_arg = '--log-level=0' if self.is_chromeos(
876 tester_config) else '--enable-logging=stderr'
877
Kenneth Russell8a386d42018-06-02 09:48:01878 args = [
Bo Liu555a0f92019-03-29 12:11:56879 test_to_run,
880 '--show-stdout',
881 '--browser=%s' % browser,
882 # --passthrough displays more of the logging in Telemetry when
883 # run via typ, in particular some of the warnings about tests
884 # being expected to fail, but passing.
885 '--passthrough',
886 '-v',
Brian Sheedy4053a702020-07-28 02:09:52887 '--extra-browser-args=%s --js-flags=--expose-gc' % logging_arg,
Kenneth Russell8a386d42018-06-02 09:48:01888 ] + args
889 result['args'] = self.maybe_fixup_args_array(self.substitute_gpu_args(
Stephen Martinis2a0667022018-09-25 22:31:14890 tester_config, result['swarming'], args))
Kenneth Russell8a386d42018-06-02 09:48:01891 return result
892
Kenneth Russelleb60cbd22017-12-05 07:54:28893 def get_test_generator_map(self):
894 return {
Bo Liu555a0f92019-03-29 12:11:56895 'android_webview_gpu_telemetry_tests':
896 GPUTelemetryTestGenerator(self, is_android_webview=True),
Bo Liu555a0f92019-03-29 12:11:56897 'gpu_telemetry_tests':
898 GPUTelemetryTestGenerator(self),
899 'gtest_tests':
900 GTestGenerator(self),
Bo Liu555a0f92019-03-29 12:11:56901 'isolated_scripts':
902 IsolatedScriptTestGenerator(self),
903 'junit_tests':
904 JUnitGenerator(self),
905 'scripts':
906 ScriptGenerator(self),
Kenneth Russelleb60cbd22017-12-05 07:54:28907 }
908
Kenneth Russell8a386d42018-06-02 09:48:01909 def get_test_type_remapper(self):
910 return {
911 # These are a specialization of isolated_scripts with a bunch of
912 # boilerplate command line arguments added to each one.
Bo Liu555a0f92019-03-29 12:11:56913 'android_webview_gpu_telemetry_tests': 'isolated_scripts',
Kenneth Russell8a386d42018-06-02 09:48:01914 'gpu_telemetry_tests': 'isolated_scripts',
915 }
916
Jeff Yoon67c3e832020-02-08 07:39:38917 def check_composition_type_test_suites(self, test_type,
918 additional_validators=None):
919 """Pre-pass to catch errors reliabily for compound/matrix suites"""
920 validators = [check_compound_references,
921 check_basic_references,
922 check_conflicting_definitions]
923 if additional_validators:
924 validators += additional_validators
925
926 target_suites = self.test_suites.get(test_type, {})
927 other_test_type = ('compound_suites'
928 if test_type == 'matrix_compound_suites'
929 else 'matrix_compound_suites')
930 other_suites = self.test_suites.get(other_test_type, {})
Jeff Yoon8154e582019-12-03 23:30:01931 basic_suites = self.test_suites.get('basic_suites', {})
932
Jeff Yoon67c3e832020-02-08 07:39:38933 for suite, suite_def in target_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:01934 if suite in basic_suites:
935 raise BBGenErr('%s names may not duplicate basic test suite names '
936 '(error found while processsing %s)'
937 % (test_type, suite))
Nodir Turakulov28232afd2019-12-17 18:02:01938
Jeff Yoon67c3e832020-02-08 07:39:38939 seen_tests = {}
940 for sub_suite in suite_def:
941 for validator in validators:
942 validator(
943 basic_suites=basic_suites,
944 other_test_suites=other_suites,
945 seen_tests=seen_tests,
946 sub_suite=sub_suite,
947 suite=suite,
948 suite_def=suite_def,
949 target_test_suites=target_suites,
950 test_type=test_type,
Jeff Yoonda581c32020-03-06 03:56:05951 all_variants=self.variants
Jeff Yoon67c3e832020-02-08 07:39:38952 )
Kenneth Russelleb60cbd22017-12-05 07:54:28953
Stephen Martinis54d64ad2018-09-21 22:16:20954 def flatten_test_suites(self):
955 new_test_suites = {}
Jeff Yoon8154e582019-12-03 23:30:01956 test_types = ['basic_suites', 'compound_suites', 'matrix_compound_suites']
957 for category in test_types:
958 for name, value in self.test_suites.get(category, {}).iteritems():
959 new_test_suites[name] = value
Stephen Martinis54d64ad2018-09-21 22:16:20960 self.test_suites = new_test_suites
961
Chan Lia3ad1502020-04-28 05:32:11962 def resolve_test_id_prefixes(self):
Nodir Turakulovfce34292019-12-18 17:05:41963 for suite in self.test_suites['basic_suites'].itervalues():
964 for key, test in suite.iteritems():
Dirk Pranke0e879b22020-07-16 23:53:56965 assert isinstance(test, dict)
Nodir Turakulovfce34292019-12-18 17:05:41966
967 # This assumes the recipe logic which prefers 'test' to 'isolate_name'
968 # https://source.chromium.org/chromium/chromium/tools/build/+/master:scripts/slave/recipe_modules/chromium_tests/generators.py;l=89;drc=14c062ba0eb418d3c4623dde41a753241b9df06b
969 # TODO(crbug.com/1035124): clean this up.
970 isolate_name = test.get('test') or test.get('isolate_name') or key
971 gn_entry = self.gn_isolate_map.get(isolate_name)
972 if gn_entry:
Corentin Wallez55b8e772020-04-24 17:39:28973 label = gn_entry['label']
974
975 if label.count(':') != 1:
976 raise BBGenErr(
977 'Malformed GN label "%s" in gn_isolate_map for key "%s",'
978 ' implicit names (like //f/b meaning //f/b:b) are disallowed.' %
979 (label, isolate_name))
980 if label.split(':')[1] != isolate_name:
981 raise BBGenErr(
982 'gn_isolate_map key name "%s" doesn\'t match GN target name in'
983 ' label "%s" see http://crbug.com/1071091 for details.' %
984 (isolate_name, label))
985
Chan Lia3ad1502020-04-28 05:32:11986 test['test_id_prefix'] = 'ninja:%s/' % label
Nodir Turakulovfce34292019-12-18 17:05:41987 else: # pragma: no cover
988 # Some tests do not have an entry gn_isolate_map.pyl, such as
989 # telemetry tests.
990 # TODO(crbug.com/1035304): require an entry in gn_isolate_map.
991 pass
992
Kenneth Russelleb60cbd22017-12-05 07:54:28993 def resolve_composition_test_suites(self):
Jeff Yoon8154e582019-12-03 23:30:01994 self.check_composition_type_test_suites('compound_suites')
Stephen Martinis54d64ad2018-09-21 22:16:20995
Jeff Yoon8154e582019-12-03 23:30:01996 compound_suites = self.test_suites.get('compound_suites', {})
997 # check_composition_type_test_suites() checks that all basic suites
998 # referenced by compound suites exist.
999 basic_suites = self.test_suites.get('basic_suites')
1000
1001 for name, value in compound_suites.iteritems():
1002 # Resolve this to a dictionary.
1003 full_suite = {}
1004 for entry in value:
1005 suite = basic_suites[entry]
1006 full_suite.update(suite)
1007 compound_suites[name] = full_suite
1008
Jeff Yoon85fb8df2020-08-20 16:47:431009 def resolve_variants(self, basic_test_definition, variants, mixins):
Jeff Yoon67c3e832020-02-08 07:39:381010 """ Merge variant-defined configurations to each test case definition in a
1011 test suite.
1012
1013 The output maps a unique test name to an array of configurations because
1014 there may exist more than one definition for a test name using variants. The
1015 test name is referenced while mapping machines to test suites, so unpacking
1016 the array is done by the generators.
1017
1018 Args:
1019 basic_test_definition: a {} defined test suite in the format
1020 test_name:test_config
1021 variants: an [] of {} defining configurations to be applied to each test
1022 case in the basic test_definition
1023
1024 Return:
1025 a {} of test_name:[{}], where each {} is a merged configuration
1026 """
1027
1028 # Each test in a basic test suite will have a definition per variant.
1029 test_suite = {}
1030 for test_name, test_config in basic_test_definition.iteritems():
1031 definitions = []
1032 for variant in variants:
Jeff Yoonda581c32020-03-06 03:56:051033 # Unpack the variant from variants.pyl if it's string based.
1034 if isinstance(variant, str):
1035 variant = self.variants[variant]
1036
Jeff Yoon67c3e832020-02-08 07:39:381037 # Clone a copy of test_config so that we can have a uniquely updated
1038 # version of it per variant
1039 cloned_config = copy.deepcopy(test_config)
1040 # The variant definition needs to be re-used for each test, so we'll
1041 # create a clone and work with it as well.
1042 cloned_variant = copy.deepcopy(variant)
1043
1044 cloned_config['args'] = (cloned_config.get('args', []) +
1045 cloned_variant.get('args', []))
1046 cloned_config['mixins'] = (cloned_config.get('mixins', []) +
Jeff Yoon85fb8df2020-08-20 16:47:431047 cloned_variant.get('mixins', []) + mixins)
Jeff Yoon67c3e832020-02-08 07:39:381048
1049 basic_swarming_def = cloned_config.get('swarming', {})
1050 variant_swarming_def = cloned_variant.get('swarming', {})
1051 if basic_swarming_def and variant_swarming_def:
1052 if ('dimension_sets' in basic_swarming_def and
1053 'dimension_sets' in variant_swarming_def):
1054 # Retain swarming dimension set merge behavior when both variant and
1055 # the basic test configuration both define it
1056 self.dictionary_merge(basic_swarming_def, variant_swarming_def)
1057 # Remove dimension_sets from the variant definition, so that it does
1058 # not replace what's been done by dictionary_merge in the update
1059 # call below.
1060 del variant_swarming_def['dimension_sets']
1061
1062 # Update the swarming definition with whatever is defined for swarming
1063 # by the variant.
1064 basic_swarming_def.update(variant_swarming_def)
1065 cloned_config['swarming'] = basic_swarming_def
1066
1067 # The identifier is used to make the name of the test unique.
1068 # Generators in the recipe uniquely identify a test by it's name, so we
1069 # don't want to have the same name for each variant.
1070 cloned_config['name'] = '{}_{}'.format(test_name,
1071 cloned_variant['identifier'])
Jeff Yoon67c3e832020-02-08 07:39:381072 definitions.append(cloned_config)
1073 test_suite[test_name] = definitions
1074 return test_suite
1075
Jeff Yoon8154e582019-12-03 23:30:011076 def resolve_matrix_compound_test_suites(self):
Jeff Yoon67c3e832020-02-08 07:39:381077 self.check_composition_type_test_suites('matrix_compound_suites',
1078 [check_matrix_identifier])
Jeff Yoon8154e582019-12-03 23:30:011079
1080 matrix_compound_suites = self.test_suites.get('matrix_compound_suites', {})
Jeff Yoon67c3e832020-02-08 07:39:381081 # check_composition_type_test_suites() checks that all basic suites are
Jeff Yoon8154e582019-12-03 23:30:011082 # referenced by matrix suites exist.
1083 basic_suites = self.test_suites.get('basic_suites')
1084
Jeff Yoon67c3e832020-02-08 07:39:381085 for test_name, matrix_config in matrix_compound_suites.iteritems():
Jeff Yoon8154e582019-12-03 23:30:011086 full_suite = {}
Jeff Yoon67c3e832020-02-08 07:39:381087
1088 for test_suite, mtx_test_suite_config in matrix_config.iteritems():
1089 basic_test_def = copy.deepcopy(basic_suites[test_suite])
1090
1091 if 'variants' in mtx_test_suite_config:
Jeff Yoon85fb8df2020-08-20 16:47:431092 mixins = mtx_test_suite_config.get('mixins', [])
Jeff Yoon67c3e832020-02-08 07:39:381093 result = self.resolve_variants(basic_test_def,
Jeff Yoon85fb8df2020-08-20 16:47:431094 mtx_test_suite_config['variants'],
1095 mixins)
Jeff Yoon67c3e832020-02-08 07:39:381096 full_suite.update(result)
1097 matrix_compound_suites[test_name] = full_suite
Kenneth Russelleb60cbd22017-12-05 07:54:281098
1099 def link_waterfalls_to_test_suites(self):
1100 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431101 for tester_name, tester in waterfall['machines'].iteritems():
1102 for suite, value in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281103 if not value in self.test_suites:
1104 # Hard / impossible to cover this in the unit test.
1105 raise self.unknown_test_suite(
1106 value, tester_name, waterfall['name']) # pragma: no cover
1107 tester['test_suites'][suite] = self.test_suites[value]
1108
1109 def load_configuration_files(self):
1110 self.waterfalls = self.load_pyl_file('waterfalls.pyl')
1111 self.test_suites = self.load_pyl_file('test_suites.pyl')
1112 self.exceptions = self.load_pyl_file('test_suite_exceptions.pyl')
Stephen Martinisb72f6d22018-10-04 23:29:011113 self.mixins = self.load_pyl_file('mixins.pyl')
Nodir Turakulovfce34292019-12-18 17:05:411114 self.gn_isolate_map = self.load_pyl_file('gn_isolate_map.pyl')
Jeff Yoonda581c32020-03-06 03:56:051115 self.variants = self.load_pyl_file('variants.pyl')
Kenneth Russelleb60cbd22017-12-05 07:54:281116
1117 def resolve_configuration_files(self):
Chan Lia3ad1502020-04-28 05:32:111118 self.resolve_test_id_prefixes()
Kenneth Russelleb60cbd22017-12-05 07:54:281119 self.resolve_composition_test_suites()
Jeff Yoon8154e582019-12-03 23:30:011120 self.resolve_matrix_compound_test_suites()
1121 self.flatten_test_suites()
Kenneth Russelleb60cbd22017-12-05 07:54:281122 self.link_waterfalls_to_test_suites()
1123
Nico Weberd18b8962018-05-16 19:39:381124 def unknown_bot(self, bot_name, waterfall_name):
1125 return BBGenErr(
1126 'Unknown bot name "%s" on waterfall "%s"' % (bot_name, waterfall_name))
1127
Kenneth Russelleb60cbd22017-12-05 07:54:281128 def unknown_test_suite(self, suite_name, bot_name, waterfall_name):
1129 return BBGenErr(
Nico Weberd18b8962018-05-16 19:39:381130 'Test suite %s from machine %s on waterfall %s not present in '
Kenneth Russelleb60cbd22017-12-05 07:54:281131 'test_suites.pyl' % (suite_name, bot_name, waterfall_name))
1132
1133 def unknown_test_suite_type(self, suite_type, bot_name, waterfall_name):
1134 return BBGenErr(
1135 'Unknown test suite type ' + suite_type + ' in bot ' + bot_name +
1136 ' on waterfall ' + waterfall_name)
1137
Stephen Martinisb72f6d22018-10-04 23:29:011138 def apply_all_mixins(self, test, waterfall, builder_name, builder):
Stephen Martinis0382bc12018-09-17 22:29:071139 """Applies all present swarming mixins to the test for a given builder.
Stephen Martinisb6a50492018-09-12 23:59:321140
1141 Checks in the waterfall, builder, and test objects for mixins.
1142 """
1143 def valid_mixin(mixin_name):
1144 """Asserts that the mixin is valid."""
Stephen Martinisb72f6d22018-10-04 23:29:011145 if mixin_name not in self.mixins:
Stephen Martinisb6a50492018-09-12 23:59:321146 raise BBGenErr("bad mixin %s" % mixin_name)
Jeff Yoon67c3e832020-02-08 07:39:381147
Stephen Martinisb6a50492018-09-12 23:59:321148 def must_be_list(mixins, typ, name):
1149 """Asserts that given mixins are a list."""
1150 if not isinstance(mixins, list):
1151 raise BBGenErr("'%s' in %s '%s' must be a list" % (mixins, typ, name))
1152
Brian Sheedy7658c982020-01-08 02:27:581153 test_name = test.get('name')
1154 remove_mixins = set()
1155 if 'remove_mixins' in builder:
1156 must_be_list(builder['remove_mixins'], 'builder', builder_name)
1157 for rm in builder['remove_mixins']:
1158 valid_mixin(rm)
1159 remove_mixins.add(rm)
1160 if 'remove_mixins' in test:
1161 must_be_list(test['remove_mixins'], 'test', test_name)
1162 for rm in test['remove_mixins']:
1163 valid_mixin(rm)
1164 remove_mixins.add(rm)
1165 del test['remove_mixins']
1166
Stephen Martinisb72f6d22018-10-04 23:29:011167 if 'mixins' in waterfall:
1168 must_be_list(waterfall['mixins'], 'waterfall', waterfall['name'])
1169 for mixin in waterfall['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581170 if mixin in remove_mixins:
1171 continue
Stephen Martinisb6a50492018-09-12 23:59:321172 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011173 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321174
Stephen Martinisb72f6d22018-10-04 23:29:011175 if 'mixins' in builder:
1176 must_be_list(builder['mixins'], 'builder', builder_name)
1177 for mixin in builder['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581178 if mixin in remove_mixins:
1179 continue
Stephen Martinisb6a50492018-09-12 23:59:321180 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011181 test = self.apply_mixin(self.mixins[mixin], test)
Stephen Martinisb6a50492018-09-12 23:59:321182
Stephen Martinisb72f6d22018-10-04 23:29:011183 if not 'mixins' in test:
Stephen Martinis0382bc12018-09-17 22:29:071184 return test
1185
Stephen Martinis2a0667022018-09-25 22:31:141186 if not test_name:
1187 test_name = test.get('test')
1188 if not test_name: # pragma: no cover
1189 # Not the best name, but we should say something.
1190 test_name = str(test)
Stephen Martinisb72f6d22018-10-04 23:29:011191 must_be_list(test['mixins'], 'test', test_name)
1192 for mixin in test['mixins']:
Brian Sheedy7658c982020-01-08 02:27:581193 # We don't bother checking if the given mixin is in remove_mixins here
1194 # since this is already the lowest level, so if a mixin is added here that
1195 # we don't want, we can just delete its entry.
Stephen Martinis0382bc12018-09-17 22:29:071196 valid_mixin(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011197 test = self.apply_mixin(self.mixins[mixin], test)
Jeff Yoon67c3e832020-02-08 07:39:381198 del test['mixins']
Stephen Martinis0382bc12018-09-17 22:29:071199 return test
Stephen Martinisb6a50492018-09-12 23:59:321200
Stephen Martinisb72f6d22018-10-04 23:29:011201 def apply_mixin(self, mixin, test):
1202 """Applies a mixin to a test.
Stephen Martinisb6a50492018-09-12 23:59:321203
Stephen Martinis0382bc12018-09-17 22:29:071204 Mixins will not override an existing key. This is to ensure exceptions can
1205 override a setting a mixin applies.
1206
Stephen Martinisb72f6d22018-10-04 23:29:011207 Swarming dimensions are handled in a special way. Instead of specifying
Stephen Martinisb6a50492018-09-12 23:59:321208 'dimension_sets', which is how normal test suites specify their dimensions,
1209 you specify a 'dimensions' key, which maps to a dictionary. This dictionary
1210 is then applied to every dimension set in the test.
Stephen Martinisb72f6d22018-10-04 23:29:011211
Stephen Martinisb6a50492018-09-12 23:59:321212 """
1213 new_test = copy.deepcopy(test)
1214 mixin = copy.deepcopy(mixin)
Stephen Martinisb72f6d22018-10-04 23:29:011215 if 'swarming' in mixin:
1216 swarming_mixin = mixin['swarming']
1217 new_test.setdefault('swarming', {})
Brian Sheedycae63b22020-06-10 22:52:111218 # Copy over any explicit dimension sets first so that they will be updated
1219 # by any subsequent 'dimensions' entries.
1220 if 'dimension_sets' in swarming_mixin:
1221 existing_dimension_sets = new_test['swarming'].setdefault(
1222 'dimension_sets', [])
1223 # Appending to the existing list could potentially result in different
1224 # behavior depending on the order the mixins were applied, but that's
1225 # already the case for other parts of mixins, so trust that the user
1226 # will verify that the generated output is correct before submitting.
1227 for dimension_set in swarming_mixin['dimension_sets']:
1228 if dimension_set not in existing_dimension_sets:
1229 existing_dimension_sets.append(dimension_set)
1230 del swarming_mixin['dimension_sets']
Stephen Martinisb72f6d22018-10-04 23:29:011231 if 'dimensions' in swarming_mixin:
1232 new_test['swarming'].setdefault('dimension_sets', [{}])
1233 for dimension_set in new_test['swarming']['dimension_sets']:
1234 dimension_set.update(swarming_mixin['dimensions'])
1235 del swarming_mixin['dimensions']
Stephen Martinisb72f6d22018-10-04 23:29:011236 # python dict update doesn't do recursion at all. Just hard code the
1237 # nested update we need (mixin['swarming'] shouldn't clobber
1238 # test['swarming'], but should update it).
1239 new_test['swarming'].update(swarming_mixin)
1240 del mixin['swarming']
1241
Wezc0e835b702018-10-30 00:38:411242 if '$mixin_append' in mixin:
1243 # Values specified under $mixin_append should be appended to existing
1244 # lists, rather than replacing them.
1245 mixin_append = mixin['$mixin_append']
1246 for key in mixin_append:
1247 new_test.setdefault(key, [])
1248 if not isinstance(mixin_append[key], list):
1249 raise BBGenErr(
1250 'Key "' + key + '" in $mixin_append must be a list.')
1251 if not isinstance(new_test[key], list):
1252 raise BBGenErr(
1253 'Cannot apply $mixin_append to non-list "' + key + '".')
1254 new_test[key].extend(mixin_append[key])
1255 if 'args' in mixin_append:
1256 new_test['args'] = self.maybe_fixup_args_array(new_test['args'])
1257 del mixin['$mixin_append']
1258
Stephen Martinisb72f6d22018-10-04 23:29:011259 new_test.update(mixin)
Stephen Martinisb6a50492018-09-12 23:59:321260 return new_test
1261
Greg Gutermanf60eb052020-03-12 17:40:011262 def generate_output_tests(self, waterfall):
1263 """Generates the tests for a waterfall.
1264
1265 Args:
1266 waterfall: a dictionary parsed from a master pyl file
1267 Returns:
1268 A dictionary mapping builders to test specs
1269 """
1270 return {
1271 name: self.get_tests_for_config(waterfall, name, config)
1272 for name, config
1273 in waterfall['machines'].iteritems()
1274 }
1275
1276 def get_tests_for_config(self, waterfall, name, config):
Greg Guterman5c6144152020-02-28 20:08:531277 generator_map = self.get_test_generator_map()
1278 test_type_remapper = self.get_test_type_remapper()
Kenneth Russelleb60cbd22017-12-05 07:54:281279
Greg Gutermanf60eb052020-03-12 17:40:011280 tests = {}
1281 # Copy only well-understood entries in the machine's configuration
1282 # verbatim into the generated JSON.
1283 if 'additional_compile_targets' in config:
1284 tests['additional_compile_targets'] = config[
1285 'additional_compile_targets']
1286 for test_type, input_tests in config.get('test_suites', {}).iteritems():
1287 if test_type not in generator_map:
1288 raise self.unknown_test_suite_type(
1289 test_type, name, waterfall['name']) # pragma: no cover
1290 test_generator = generator_map[test_type]
1291 # Let multiple kinds of generators generate the same kinds
1292 # of tests. For example, gpu_telemetry_tests are a
1293 # specialization of isolated_scripts.
1294 new_tests = test_generator.generate(
1295 waterfall, name, config, input_tests)
1296 remapped_test_type = test_type_remapper.get(test_type, test_type)
1297 tests[remapped_test_type] = test_generator.sort(
1298 tests.get(remapped_test_type, []) + new_tests)
1299
1300 return tests
1301
1302 def jsonify(self, all_tests):
1303 return json.dumps(
1304 all_tests, indent=2, separators=(',', ': '),
1305 sort_keys=True) + '\n'
1306
1307 def generate_outputs(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281308 self.load_configuration_files()
1309 self.resolve_configuration_files()
1310 filters = self.args.waterfall_filters
Greg Gutermanf60eb052020-03-12 17:40:011311 result = collections.defaultdict(dict)
1312
1313 required_fields = ('project', 'bucket', 'name')
1314 for waterfall in self.waterfalls:
1315 for field in required_fields:
1316 # Verify required fields
1317 if field not in waterfall:
1318 raise BBGenErr("Waterfall %s has no %s" % (waterfall['name'], field))
1319
1320 # Handle filter flag, if specified
1321 if filters and waterfall['name'] not in filters:
1322 continue
1323
1324 # Join config files and hardcoded values together
1325 all_tests = self.generate_output_tests(waterfall)
1326 result[waterfall['name']] = all_tests
1327
1328 # Deduce per-bucket mappings
1329 # This will be the standard after masternames are gone
1330 bucket_filename = waterfall['project'] + '.' + waterfall['bucket']
1331 for buildername in waterfall['machines'].keys():
1332 result[bucket_filename][buildername] = all_tests[buildername]
1333
1334 # Add do not edit warning
1335 for tests in result.values():
1336 tests['AAAAA1 AUTOGENERATED FILE DO NOT EDIT'] = {}
1337 tests['AAAAA2 See generate_buildbot_json.py to make changes'] = {}
1338
1339 return result
1340
1341 def write_json_result(self, result): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281342 suffix = '.json'
1343 if self.args.new_files:
1344 suffix = '.new' + suffix
Greg Gutermanf60eb052020-03-12 17:40:011345
1346 for filename, contents in result.items():
1347 jsonstr = self.jsonify(contents)
1348 self.write_file(self.pyl_file_path(filename + suffix), jsonstr)
Kenneth Russelleb60cbd22017-12-05 07:54:281349
Nico Weberd18b8962018-05-16 19:39:381350 def get_valid_bot_names(self):
John Budorick699282e2019-02-13 01:27:331351 # Extract bot names from infra/config/luci-milo.cfg.
Stephen Martinis26627cf2018-12-19 01:51:421352 # NOTE: This reference can cause issues; if a file changes there, the
1353 # presubmit here won't be run by default. A manually maintained list there
1354 # tries to run presubmit here when luci-milo.cfg is changed. If any other
1355 # references to configs outside of this directory are added, please change
1356 # their presubmit to run `generate_buildbot_json.py -c`, so that the tree
1357 # never ends up in an invalid state.
Garrett Beaty4f3e9212020-06-25 20:21:491358
1359 # Get the generated project.pyl so we can check if we should be enforcing
1360 # that the specs are for builders that actually exist
1361 # If not, return None to indicate that we won't enforce that builders in
1362 # waterfalls.pyl are defined in LUCI
1363 project_pyl_path = os.path.join(self.args.infra_config_dir, 'generated',
1364 'project.pyl')
1365 if os.path.exists(project_pyl_path):
1366 settings = ast.literal_eval(self.read_file(project_pyl_path))
1367 if not settings.get('validate_source_side_specs_have_builder', True):
1368 return None
1369
Nico Weberd18b8962018-05-16 19:39:381370 bot_names = set()
Garrett Beatyd5ca75962020-05-07 16:58:311371 milo_configs = glob.glob(
1372 os.path.join(self.args.infra_config_dir, 'generated', 'luci-milo*.cfg'))
John Budorickc12abd12018-08-14 19:37:431373 for c in milo_configs:
1374 for l in self.read_file(c).splitlines():
1375 if (not 'name: "buildbucket/luci.chromium.' in l and
Garrett Beatyd5ca75962020-05-07 16:58:311376 not 'name: "buildbucket/luci.chrome.' in l):
John Budorickc12abd12018-08-14 19:37:431377 continue
1378 # l looks like
1379 # `name: "buildbucket/luci.chromium.try/win_chromium_dbg_ng"`
1380 # Extract win_chromium_dbg_ng part.
1381 bot_names.add(l[l.rindex('/') + 1:l.rindex('"')])
Nico Weberd18b8962018-05-16 19:39:381382 return bot_names
1383
Ben Pastene9a010082019-09-25 20:41:371384 def get_builders_that_do_not_actually_exist(self):
Kenneth Russell8a386d42018-06-02 09:48:011385 # Some of the bots on the chromium.gpu.fyi waterfall in particular
1386 # are defined only to be mirrored into trybots, and don't actually
1387 # exist on any of the waterfalls or consoles.
1388 return [
Yuke Liao8373de52020-08-14 18:30:541389 'GPU FYI Fuchsia Builder',
1390 'ANGLE GPU Android Release (Nexus 5X)',
1391 'ANGLE GPU Linux Release (Intel HD 630)',
1392 'ANGLE GPU Linux Release (NVIDIA)',
1393 'ANGLE GPU Mac Release (Intel)',
1394 'ANGLE GPU Mac Retina Release (AMD)',
1395 'ANGLE GPU Mac Retina Release (NVIDIA)',
1396 'ANGLE GPU Win10 x64 Release (Intel HD 630)',
1397 'ANGLE GPU Win10 x64 Release (NVIDIA)',
1398 'Optional Android Release (Nexus 5X)',
1399 'Optional Linux Release (Intel HD 630)',
1400 'Optional Linux Release (NVIDIA)',
1401 'Optional Mac Release (Intel)',
1402 'Optional Mac Retina Release (AMD)',
1403 'Optional Mac Retina Release (NVIDIA)',
1404 'Optional Win10 x64 Release (Intel HD 630)',
1405 'Optional Win10 x64 Release (NVIDIA)',
1406 'Win7 ANGLE Tryserver (AMD)',
1407 # chromium.chromiumos
1408 'linux-lacros-rel',
1409 # chromium.fyi
1410 'linux-blink-rel-dummy',
1411 'linux-blink-optional-highdpi-rel-dummy',
1412 'mac10.12-blink-rel-dummy',
1413 'mac10.13-blink-rel-dummy',
1414 'mac10.14-blink-rel-dummy',
1415 'mac10.15-blink-rel-dummy',
1416 'win7-blink-rel-dummy',
1417 'win10-blink-rel-dummy',
1418 'WebKit Linux composite_after_paint Dummy Builder',
1419 'WebKit Linux layout_ng_disabled Builder',
1420 # chromium, due to https://crbug.com/878915
1421 'win-dbg',
1422 'win32-dbg',
1423 'win-archive-dbg',
1424 'win32-archive-dbg',
1425 # TODO(crbug.com/1033753) Delete these when coverage is enabled by
1426 # default on Windows tryjobs.
1427 'GPU Win x64 Builder Code Coverage',
1428 'Win x64 Builder Code Coverage',
1429 'Win10 Tests x64 Code Coverage',
1430 'Win10 x64 Release (NVIDIA) Code Coverage',
1431 # TODO(crbug.com/1024915) Delete these when coverage is enabled by
1432 # default on Mac OS tryjobs.
1433 'Mac Builder Code Coverage',
1434 'Mac10.13 Tests Code Coverage',
1435 'GPU Mac Builder Code Coverage',
1436 'Mac Release (Intel) Code Coverage',
1437 'Mac Retina Release (AMD) Code Coverage',
Kenneth Russell8a386d42018-06-02 09:48:011438 ]
1439
Ben Pastene9a010082019-09-25 20:41:371440 def get_internal_waterfalls(self):
1441 # Similar to get_builders_that_do_not_actually_exist above, but for
1442 # waterfalls defined in internal configs.
Jeff Yoon8acfdce2020-04-20 22:38:071443 return ['chrome', 'chrome.pgo']
Ben Pastene9a010082019-09-25 20:41:371444
Stephen Martinisf83893722018-09-19 00:02:181445 def check_input_file_consistency(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201446 self.check_input_files_sorting(verbose)
1447
Kenneth Russelleb60cbd22017-12-05 07:54:281448 self.load_configuration_files()
Jeff Yoon8154e582019-12-03 23:30:011449 self.check_composition_type_test_suites('compound_suites')
Jeff Yoon67c3e832020-02-08 07:39:381450 self.check_composition_type_test_suites('matrix_compound_suites',
1451 [check_matrix_identifier])
Chan Lia3ad1502020-04-28 05:32:111452 self.resolve_test_id_prefixes()
Stephen Martinis54d64ad2018-09-21 22:16:201453 self.flatten_test_suites()
Nico Weberd18b8962018-05-16 19:39:381454
1455 # All bots should exist.
1456 bot_names = self.get_valid_bot_names()
Ben Pastene9a010082019-09-25 20:41:371457 builders_that_dont_exist = self.get_builders_that_do_not_actually_exist()
Garrett Beaty2a02de3c2020-05-15 13:57:351458 if bot_names is not None:
1459 internal_waterfalls = self.get_internal_waterfalls()
1460 for waterfall in self.waterfalls:
1461 # TODO(crbug.com/991417): Remove the need for this exception.
1462 if waterfall['name'] in internal_waterfalls:
Kenneth Russell8a386d42018-06-02 09:48:011463 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351464 for bot_name in waterfall['machines']:
1465 if bot_name in builders_that_dont_exist:
Kenneth Russell78fd8702018-05-17 01:15:521466 continue # pragma: no cover
Garrett Beaty2a02de3c2020-05-15 13:57:351467 if bot_name not in bot_names:
1468 if waterfall['name'] in ['client.v8.chromium', 'client.v8.fyi']:
1469 # TODO(thakis): Remove this once these bots move to luci.
1470 continue # pragma: no cover
1471 if waterfall['name'] in ['tryserver.webrtc',
1472 'webrtc.chromium.fyi.experimental']:
1473 # These waterfalls have their bot configs in a different repo.
1474 # so we don't know about their bot names.
1475 continue # pragma: no cover
1476 if waterfall['name'] in ['client.devtools-frontend.integration',
1477 'tryserver.devtools-frontend',
1478 'chromium.devtools-frontend']:
1479 continue # pragma: no cover
1480 raise self.unknown_bot(bot_name, waterfall['name'])
Nico Weberd18b8962018-05-16 19:39:381481
Kenneth Russelleb60cbd22017-12-05 07:54:281482 # All test suites must be referenced.
1483 suites_seen = set()
1484 generator_map = self.get_test_generator_map()
1485 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431486 for bot_name, tester in waterfall['machines'].iteritems():
1487 for suite_type, suite in tester.get('test_suites', {}).iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281488 if suite_type not in generator_map:
1489 raise self.unknown_test_suite_type(suite_type, bot_name,
1490 waterfall['name'])
1491 if suite not in self.test_suites:
1492 raise self.unknown_test_suite(suite, bot_name, waterfall['name'])
1493 suites_seen.add(suite)
1494 # Since we didn't resolve the configuration files, this set
1495 # includes both composition test suites and regular ones.
1496 resolved_suites = set()
1497 for suite_name in suites_seen:
1498 suite = self.test_suites[suite_name]
Jeff Yoon8154e582019-12-03 23:30:011499 for sub_suite in suite:
1500 resolved_suites.add(sub_suite)
Kenneth Russelleb60cbd22017-12-05 07:54:281501 resolved_suites.add(suite_name)
1502 # At this point, every key in test_suites.pyl should be referenced.
1503 missing_suites = set(self.test_suites.keys()) - resolved_suites
1504 if missing_suites:
1505 raise BBGenErr('The following test suites were unreferenced by bots on '
1506 'the waterfalls: ' + str(missing_suites))
1507
1508 # All test suite exceptions must refer to bots on the waterfall.
1509 all_bots = set()
1510 missing_bots = set()
1511 for waterfall in self.waterfalls:
Kenneth Russell139f8642017-12-05 08:51:431512 for bot_name, tester in waterfall['machines'].iteritems():
Kenneth Russelleb60cbd22017-12-05 07:54:281513 all_bots.add(bot_name)
Kenneth Russell8ceeabf2017-12-11 17:53:281514 # In order to disambiguate between bots with the same name on
1515 # different waterfalls, support has been added to various
1516 # exceptions for concatenating the waterfall name after the bot
1517 # name.
1518 all_bots.add(bot_name + ' ' + waterfall['name'])
Kenneth Russelleb60cbd22017-12-05 07:54:281519 for exception in self.exceptions.itervalues():
Nico Weberd18b8962018-05-16 19:39:381520 removals = (exception.get('remove_from', []) +
1521 exception.get('remove_gtest_from', []) +
1522 exception.get('modifications', {}).keys())
1523 for removal in removals:
Kenneth Russelleb60cbd22017-12-05 07:54:281524 if removal not in all_bots:
1525 missing_bots.add(removal)
Stephen Martiniscc70c962018-07-31 21:22:411526
Ben Pastene9a010082019-09-25 20:41:371527 missing_bots = missing_bots - set(builders_that_dont_exist)
Kenneth Russelleb60cbd22017-12-05 07:54:281528 if missing_bots:
1529 raise BBGenErr('The following nonexistent machines were referenced in '
1530 'the test suite exceptions: ' + str(missing_bots))
1531
Stephen Martinis0382bc12018-09-17 22:29:071532 # All mixins must be referenced
1533 seen_mixins = set()
1534 for waterfall in self.waterfalls:
Stephen Martinisb72f6d22018-10-04 23:29:011535 seen_mixins = seen_mixins.union(waterfall.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071536 for bot_name, tester in waterfall['machines'].iteritems():
Stephen Martinisb72f6d22018-10-04 23:29:011537 seen_mixins = seen_mixins.union(tester.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071538 for suite in self.test_suites.values():
1539 if isinstance(suite, list):
1540 # Don't care about this, it's a composition, which shouldn't include a
1541 # swarming mixin.
1542 continue
1543
1544 for test in suite.values():
Dirk Pranke0e879b22020-07-16 23:53:561545 assert isinstance(test, dict)
Stephen Martinisb72f6d22018-10-04 23:29:011546 seen_mixins = seen_mixins.union(test.get('mixins', set()))
Stephen Martinis0382bc12018-09-17 22:29:071547
Stephen Martinisb72f6d22018-10-04 23:29:011548 missing_mixins = set(self.mixins.keys()) - seen_mixins
Stephen Martinis0382bc12018-09-17 22:29:071549 if missing_mixins:
1550 raise BBGenErr('The following mixins are unreferenced: %s. They must be'
1551 ' referenced in a waterfall, machine, or test suite.' % (
1552 str(missing_mixins)))
1553
Jeff Yoonda581c32020-03-06 03:56:051554 # All variant references must be referenced
1555 seen_variants = set()
1556 for suite in self.test_suites.values():
1557 if isinstance(suite, list):
1558 continue
1559
1560 for test in suite.values():
1561 if isinstance(test, dict):
1562 for variant in test.get('variants', []):
1563 if isinstance(variant, str):
1564 seen_variants.add(variant)
1565
1566 missing_variants = set(self.variants.keys()) - seen_variants
1567 if missing_variants:
1568 raise BBGenErr('The following variants were unreferenced: %s. They must '
1569 'be referenced in a matrix test suite under the variants '
1570 'key.' % str(missing_variants))
1571
Stephen Martinis54d64ad2018-09-21 22:16:201572
1573 def type_assert(self, node, typ, filename, verbose=False):
1574 """Asserts that the Python AST node |node| is of type |typ|.
1575
1576 If verbose is set, it prints out some helpful context lines, showing where
1577 exactly the error occurred in the file.
1578 """
1579 if not isinstance(node, typ):
1580 if verbose:
1581 lines = [""] + self.read_file(filename).splitlines()
1582
1583 context = 2
1584 lines_start = max(node.lineno - context, 0)
1585 # Add one to include the last line
1586 lines_end = min(node.lineno + context, len(lines)) + 1
1587 lines = (
1588 ['== %s ==\n' % filename] +
1589 ["<snip>\n"] +
1590 ['%d %s' % (lines_start + i, line) for i, line in enumerate(
1591 lines[lines_start:lines_start + context])] +
1592 ['-' * 80 + '\n'] +
1593 ['%d %s' % (node.lineno, lines[node.lineno])] +
1594 ['-' * (node.col_offset + 3) + '^' + '-' * (
1595 80 - node.col_offset - 4) + '\n'] +
1596 ['%d %s' % (node.lineno + 1 + i, line) for i, line in enumerate(
1597 lines[node.lineno + 1:lines_end])] +
1598 ["<snip>\n"]
1599 )
1600 # Print out a useful message when a type assertion fails.
1601 for l in lines:
1602 self.print_line(l.strip())
1603
1604 node_dumped = ast.dump(node, annotate_fields=False)
1605 # If the node is huge, truncate it so everything fits in a terminal
1606 # window.
1607 if len(node_dumped) > 60: # pragma: no cover
1608 node_dumped = node_dumped[:30] + ' <SNIP> ' + node_dumped[-30:]
1609 raise BBGenErr(
1610 'Invalid .pyl file %r. Python AST node %r on line %s expected to'
1611 ' be %s, is %s' % (
1612 filename, node_dumped,
1613 node.lineno, typ, type(node)))
1614
Stephen Martinis5bef0fc2020-01-06 22:47:531615 def check_ast_list_formatted(self, keys, filename, verbose,
Stephen Martinis1384ff92020-01-07 19:52:151616 check_sorting=True):
Stephen Martinis5bef0fc2020-01-06 22:47:531617 """Checks if a list of ast keys are correctly formatted.
Stephen Martinis54d64ad2018-09-21 22:16:201618
Stephen Martinis5bef0fc2020-01-06 22:47:531619 Currently only checks to ensure they're correctly sorted, and that there
1620 are no duplicates.
1621
1622 Args:
1623 keys: An python list of AST nodes.
1624
1625 It's a list of AST nodes instead of a list of strings because
1626 when verbose is set, it tries to print out context of where the
1627 diffs are in the file.
1628 filename: The name of the file this node is from.
1629 verbose: If set, print out diff information about how the keys are
1630 incorrectly formatted.
1631 check_sorting: If true, checks if the list is sorted.
1632 Returns:
1633 If the keys are correctly formatted.
1634 """
1635 if not keys:
1636 return True
1637
1638 assert isinstance(keys[0], ast.Str)
1639
1640 keys_strs = [k.s for k in keys]
1641 # Keys to diff against. Used below.
1642 keys_to_diff_against = None
1643 # If the list is properly formatted.
1644 list_formatted = True
1645
1646 # Duplicates are always bad.
1647 if len(set(keys_strs)) != len(keys_strs):
1648 list_formatted = False
1649 keys_to_diff_against = list(collections.OrderedDict.fromkeys(keys_strs))
1650
1651 if check_sorting and sorted(keys_strs) != keys_strs:
1652 list_formatted = False
1653 if list_formatted:
1654 return True
1655
1656 if verbose:
1657 line_num = keys[0].lineno
1658 keys = [k.s for k in keys]
1659 if check_sorting:
1660 # If we have duplicates, sorting this will take care of it anyways.
1661 keys_to_diff_against = sorted(set(keys))
1662 # else, keys_to_diff_against is set above already
1663
1664 self.print_line('=' * 80)
1665 self.print_line('(First line of keys is %s)' % line_num)
1666 for line in difflib.context_diff(
1667 keys, keys_to_diff_against,
1668 fromfile='current (%r)' % filename, tofile='sorted', lineterm=''):
1669 self.print_line(line)
1670 self.print_line('=' * 80)
1671
1672 return False
1673
Stephen Martinis1384ff92020-01-07 19:52:151674 def check_ast_dict_formatted(self, node, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531675 """Checks if an ast dictionary's keys are correctly formatted.
1676
1677 Just a simple wrapper around check_ast_list_formatted.
1678 Args:
1679 node: An AST node. Assumed to be a dictionary.
1680 filename: The name of the file this node is from.
1681 verbose: If set, print out diff information about how the keys are
1682 incorrectly formatted.
1683 check_sorting: If true, checks if the list is sorted.
1684 Returns:
1685 If the dictionary is correctly formatted.
1686 """
Stephen Martinis54d64ad2018-09-21 22:16:201687 keys = []
1688 # The keys of this dict are ordered as ordered in the file; normal python
1689 # dictionary keys are given an arbitrary order, but since we parsed the
1690 # file itself, the order as given in the file is preserved.
1691 for key in node.keys:
1692 self.type_assert(key, ast.Str, filename, verbose)
Stephen Martinis5bef0fc2020-01-06 22:47:531693 keys.append(key)
Stephen Martinis54d64ad2018-09-21 22:16:201694
Stephen Martinis1384ff92020-01-07 19:52:151695 return self.check_ast_list_formatted(keys, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181696
1697 def check_input_files_sorting(self, verbose=False):
Stephen Martinis54d64ad2018-09-21 22:16:201698 # TODO(https://crbug.com/886993): Add the ability for this script to
1699 # actually format the files, rather than just complain if they're
1700 # incorrectly formatted.
1701 bad_files = set()
Stephen Martinis5bef0fc2020-01-06 22:47:531702 def parse_file(filename):
1703 """Parses and validates a .pyl file.
Stephen Martinis54d64ad2018-09-21 22:16:201704
Stephen Martinis5bef0fc2020-01-06 22:47:531705 Returns an AST node representing the value in the pyl file."""
Stephen Martinisf83893722018-09-19 00:02:181706 parsed = ast.parse(self.read_file(self.pyl_file_path(filename)))
1707
Stephen Martinisf83893722018-09-19 00:02:181708 # Must be a module.
Stephen Martinis54d64ad2018-09-21 22:16:201709 self.type_assert(parsed, ast.Module, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181710 module = parsed.body
1711
1712 # Only one expression in the module.
Stephen Martinis54d64ad2018-09-21 22:16:201713 self.type_assert(module, list, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181714 if len(module) != 1: # pragma: no cover
1715 raise BBGenErr('Invalid .pyl file %s' % filename)
1716 expr = module[0]
Stephen Martinis54d64ad2018-09-21 22:16:201717 self.type_assert(expr, ast.Expr, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181718
Stephen Martinis5bef0fc2020-01-06 22:47:531719 return expr.value
1720
1721 # Handle this separately
1722 filename = 'waterfalls.pyl'
1723 value = parse_file(filename)
1724 # Value should be a list.
1725 self.type_assert(value, ast.List, filename, verbose)
1726
1727 keys = []
1728 for val in value.elts:
1729 self.type_assert(val, ast.Dict, filename, verbose)
1730 waterfall_name = None
1731 for key, val in zip(val.keys, val.values):
1732 self.type_assert(key, ast.Str, filename, verbose)
1733 if key.s == 'machines':
1734 if not self.check_ast_dict_formatted(val, filename, verbose):
1735 bad_files.add(filename)
1736
1737 if key.s == "name":
1738 self.type_assert(val, ast.Str, filename, verbose)
1739 waterfall_name = val
1740 assert waterfall_name
1741 keys.append(waterfall_name)
1742
Stephen Martinis1384ff92020-01-07 19:52:151743 if not self.check_ast_list_formatted(keys, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531744 bad_files.add(filename)
1745
1746 for filename in (
1747 'mixins.pyl',
1748 'test_suites.pyl',
1749 'test_suite_exceptions.pyl',
1750 ):
1751 value = parse_file(filename)
Stephen Martinisf83893722018-09-19 00:02:181752 # Value should be a dictionary.
Stephen Martinis54d64ad2018-09-21 22:16:201753 self.type_assert(value, ast.Dict, filename, verbose)
Stephen Martinisf83893722018-09-19 00:02:181754
Stephen Martinis5bef0fc2020-01-06 22:47:531755 if not self.check_ast_dict_formatted(
1756 value, filename, verbose):
1757 bad_files.add(filename)
1758
Stephen Martinis54d64ad2018-09-21 22:16:201759 if filename == 'test_suites.pyl':
Jeff Yoon8154e582019-12-03 23:30:011760 expected_keys = ['basic_suites',
1761 'compound_suites',
1762 'matrix_compound_suites']
Stephen Martinis54d64ad2018-09-21 22:16:201763 actual_keys = [node.s for node in value.keys]
1764 assert all(key in expected_keys for key in actual_keys), (
1765 'Invalid %r file; expected keys %r, got %r' % (
1766 filename, expected_keys, actual_keys))
1767 suite_dicts = [node for node in value.values]
1768 # Only two keys should mean only 1 or 2 values
Jeff Yoon8154e582019-12-03 23:30:011769 assert len(suite_dicts) <= 3
Stephen Martinis54d64ad2018-09-21 22:16:201770 for suite_group in suite_dicts:
Stephen Martinis5bef0fc2020-01-06 22:47:531771 if not self.check_ast_dict_formatted(
Stephen Martinis54d64ad2018-09-21 22:16:201772 suite_group, filename, verbose):
1773 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181774
Stephen Martinis5bef0fc2020-01-06 22:47:531775 for key, suite in zip(value.keys, value.values):
1776 # The compound suites are checked in
1777 # 'check_composition_type_test_suites()'
1778 if key.s == 'basic_suites':
1779 for group in suite.values:
Stephen Martinis1384ff92020-01-07 19:52:151780 if not self.check_ast_dict_formatted(group, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531781 bad_files.add(filename)
1782 break
Stephen Martinis54d64ad2018-09-21 22:16:201783
Stephen Martinis5bef0fc2020-01-06 22:47:531784 elif filename == 'test_suite_exceptions.pyl':
1785 # Check the values for each test.
1786 for test in value.values:
1787 for kind, node in zip(test.keys, test.values):
1788 if isinstance(node, ast.Dict):
Stephen Martinis1384ff92020-01-07 19:52:151789 if not self.check_ast_dict_formatted(node, filename, verbose):
Stephen Martinis5bef0fc2020-01-06 22:47:531790 bad_files.add(filename)
1791 elif kind.s == 'remove_from':
1792 # Don't care about sorting; these are usually grouped, since the
1793 # same bug can affect multiple builders. Do want to make sure
1794 # there aren't duplicates.
1795 if not self.check_ast_list_formatted(node.elts, filename, verbose,
1796 check_sorting=False):
1797 bad_files.add(filename)
Stephen Martinisf83893722018-09-19 00:02:181798
1799 if bad_files:
1800 raise BBGenErr(
Stephen Martinis54d64ad2018-09-21 22:16:201801 'The following files have invalid keys: %s\n. They are either '
Stephen Martinis5bef0fc2020-01-06 22:47:531802 'unsorted, or have duplicates. Re-run this with --verbose to see '
1803 'more details.' % ', '.join(bad_files))
Stephen Martinisf83893722018-09-19 00:02:181804
Kenneth Russelleb60cbd22017-12-05 07:54:281805 def check_output_file_consistency(self, verbose=False):
1806 self.load_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011807 # All waterfalls/bucket .json files must have been written
1808 # by this script already.
Kenneth Russelleb60cbd22017-12-05 07:54:281809 self.resolve_configuration_files()
Greg Gutermanf60eb052020-03-12 17:40:011810 ungenerated_files = set()
1811 for filename, expected_contents in self.generate_outputs().items():
1812 expected = self.jsonify(expected_contents)
1813 file_path = filename + '.json'
Zhiling Huangbe008172018-03-08 19:13:111814 current = self.read_file(self.pyl_file_path(file_path))
Kenneth Russelleb60cbd22017-12-05 07:54:281815 if expected != current:
Greg Gutermanf60eb052020-03-12 17:40:011816 ungenerated_files.add(filename)
John Budorick826d5ed2017-12-28 19:27:321817 if verbose: # pragma: no cover
Greg Gutermanf60eb052020-03-12 17:40:011818 self.print_line('File ' + filename +
1819 '.json did not have the following expected '
John Budorick826d5ed2017-12-28 19:27:321820 'contents:')
1821 for line in difflib.unified_diff(
1822 expected.splitlines(),
Stephen Martinis7eb8b612018-09-21 00:17:501823 current.splitlines(),
1824 fromfile='expected', tofile='current'):
1825 self.print_line(line)
Greg Gutermanf60eb052020-03-12 17:40:011826
1827 if ungenerated_files:
1828 raise BBGenErr(
1829 'The following files have not been properly '
1830 'autogenerated by generate_buildbot_json.py: ' +
1831 ', '.join([filename + '.json' for filename in ungenerated_files]))
Kenneth Russelleb60cbd22017-12-05 07:54:281832
1833 def check_consistency(self, verbose=False):
Stephen Martinis7eb8b612018-09-21 00:17:501834 self.check_input_file_consistency(verbose) # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:281835 self.check_output_file_consistency(verbose) # pragma: no cover
1836
Karen Qiane24b7ee2019-02-12 23:37:061837 def does_test_match(self, test_info, params_dict):
1838 """Checks to see if the test matches the parameters given.
1839
1840 Compares the provided test_info with the params_dict to see
1841 if the bot matches the parameters given. If so, returns True.
1842 Else, returns false.
1843
1844 Args:
1845 test_info (dict): Information about a specific bot provided
1846 in the format shown in waterfalls.pyl
1847 params_dict (dict): Dictionary of parameters and their values
1848 to look for in the bot
1849 Ex: {
1850 'device_os':'android',
1851 '--flag':True,
1852 'mixins': ['mixin1', 'mixin2'],
1853 'ex_key':'ex_value'
1854 }
1855
1856 """
1857 DIMENSION_PARAMS = ['device_os', 'device_type', 'os',
1858 'kvm', 'pool', 'integrity'] # dimension parameters
1859 SWARMING_PARAMS = ['shards', 'hard_timeout', 'idempotent',
1860 'can_use_on_swarming_builders']
1861 for param in params_dict:
1862 # if dimension parameter
1863 if param in DIMENSION_PARAMS or param in SWARMING_PARAMS:
1864 if not 'swarming' in test_info:
1865 return False
1866 swarming = test_info['swarming']
1867 if param in SWARMING_PARAMS:
1868 if not param in swarming:
1869 return False
1870 if not str(swarming[param]) == params_dict[param]:
1871 return False
1872 else:
1873 if not 'dimension_sets' in swarming:
1874 return False
1875 d_set = swarming['dimension_sets']
1876 # only looking at the first dimension set
1877 if not param in d_set[0]:
1878 return False
1879 if not d_set[0][param] == params_dict[param]:
1880 return False
1881
1882 # if flag
1883 elif param.startswith('--'):
1884 if not 'args' in test_info:
1885 return False
1886 if not param in test_info['args']:
1887 return False
1888
1889 # not dimension parameter/flag/mixin
1890 else:
1891 if not param in test_info:
1892 return False
1893 if not test_info[param] == params_dict[param]:
1894 return False
1895 return True
1896 def error_msg(self, msg):
1897 """Prints an error message.
1898
1899 In addition to a catered error message, also prints
1900 out where the user can find more help. Then, program exits.
1901 """
1902 self.print_line(msg + (' If you need more information, ' +
1903 'please run with -h or --help to see valid commands.'))
1904 sys.exit(1)
1905
1906 def find_bots_that_run_test(self, test, bots):
1907 matching_bots = []
1908 for bot in bots:
1909 bot_info = bots[bot]
1910 tests = self.flatten_tests_for_bot(bot_info)
1911 for test_info in tests:
1912 test_name = ""
1913 if 'name' in test_info:
1914 test_name = test_info['name']
1915 elif 'test' in test_info:
1916 test_name = test_info['test']
1917 if not test_name == test:
1918 continue
1919 matching_bots.append(bot)
1920 return matching_bots
1921
1922 def find_tests_with_params(self, tests, params_dict):
1923 matching_tests = []
1924 for test_name in tests:
1925 test_info = tests[test_name]
1926 if not self.does_test_match(test_info, params_dict):
1927 continue
1928 if not test_name in matching_tests:
1929 matching_tests.append(test_name)
1930 return matching_tests
1931
1932 def flatten_waterfalls_for_query(self, waterfalls):
1933 bots = {}
1934 for waterfall in waterfalls:
Greg Gutermanf60eb052020-03-12 17:40:011935 waterfall_tests = self.generate_output_tests(waterfall)
1936 for bot in waterfall_tests:
1937 bot_info = waterfall_tests[bot]
1938 bots[bot] = bot_info
Karen Qiane24b7ee2019-02-12 23:37:061939 return bots
1940
1941 def flatten_tests_for_bot(self, bot_info):
1942 """Returns a list of flattened tests.
1943
1944 Returns a list of tests not grouped by test category
1945 for a specific bot.
1946 """
1947 TEST_CATS = self.get_test_generator_map().keys()
1948 tests = []
1949 for test_cat in TEST_CATS:
1950 if not test_cat in bot_info:
1951 continue
1952 test_cat_tests = bot_info[test_cat]
1953 tests = tests + test_cat_tests
1954 return tests
1955
1956 def flatten_tests_for_query(self, test_suites):
1957 """Returns a flattened dictionary of tests.
1958
1959 Returns a dictionary of tests associate with their
1960 configuration, not grouped by their test suite.
1961 """
1962 tests = {}
1963 for test_suite in test_suites.itervalues():
1964 for test in test_suite:
1965 test_info = test_suite[test]
1966 test_name = test
1967 if 'name' in test_info:
1968 test_name = test_info['name']
1969 tests[test_name] = test_info
1970 return tests
1971
1972 def parse_query_filter_params(self, params):
1973 """Parses the filter parameters.
1974
1975 Creates a dictionary from the parameters provided
1976 to filter the bot array.
1977 """
1978 params_dict = {}
1979 for p in params:
1980 # flag
1981 if p.startswith("--"):
1982 params_dict[p] = True
1983 else:
1984 pair = p.split(":")
1985 if len(pair) != 2:
1986 self.error_msg('Invalid command.')
1987 # regular parameters
1988 if pair[1].lower() == "true":
1989 params_dict[pair[0]] = True
1990 elif pair[1].lower() == "false":
1991 params_dict[pair[0]] = False
1992 else:
1993 params_dict[pair[0]] = pair[1]
1994 return params_dict
1995
1996 def get_test_suites_dict(self, bots):
1997 """Returns a dictionary of bots and their tests.
1998
1999 Returns a dictionary of bots and a list of their associated tests.
2000 """
2001 test_suite_dict = dict()
2002 for bot in bots:
2003 bot_info = bots[bot]
2004 tests = self.flatten_tests_for_bot(bot_info)
2005 test_suite_dict[bot] = tests
2006 return test_suite_dict
2007
2008 def output_query_result(self, result, json_file=None):
2009 """Outputs the result of the query.
2010
2011 If a json file parameter name is provided, then
2012 the result is output into the json file. If not,
2013 then the result is printed to the console.
2014 """
2015 output = json.dumps(result, indent=2)
2016 if json_file:
2017 self.write_file(json_file, output)
2018 else:
2019 self.print_line(output)
2020 return
2021
2022 def query(self, args):
2023 """Queries tests or bots.
2024
2025 Depending on the arguments provided, outputs a json of
2026 tests or bots matching the appropriate optional parameters provided.
2027 """
2028 # split up query statement
2029 query = args.query.split('/')
2030 self.load_configuration_files()
2031 self.resolve_configuration_files()
2032
2033 # flatten bots json
2034 tests = self.test_suites
2035 bots = self.flatten_waterfalls_for_query(self.waterfalls)
2036
2037 cmd_class = query[0]
2038
2039 # For queries starting with 'bots'
2040 if cmd_class == "bots":
2041 if len(query) == 1:
2042 return self.output_query_result(bots, args.json)
2043 # query with specific parameters
2044 elif len(query) == 2:
2045 if query[1] == 'tests':
2046 test_suites_dict = self.get_test_suites_dict(bots)
2047 return self.output_query_result(test_suites_dict, args.json)
2048 else:
2049 self.error_msg("This query should be in the format: bots/tests.")
2050
2051 else:
2052 self.error_msg("This query should have 0 or 1 '/', found %s instead."
2053 % str(len(query)-1))
2054
2055 # For queries starting with 'bot'
2056 elif cmd_class == "bot":
2057 if not len(query) == 2 and not len(query) == 3:
2058 self.error_msg("Command should have 1 or 2 '/', found %s instead."
2059 % str(len(query)-1))
2060 bot_id = query[1]
2061 if not bot_id in bots:
2062 self.error_msg("No bot named '" + bot_id + "' found.")
2063 bot_info = bots[bot_id]
2064 if len(query) == 2:
2065 return self.output_query_result(bot_info, args.json)
2066 if not query[2] == 'tests':
2067 self.error_msg("The query should be in the format:" +
2068 "bot/<bot-name>/tests.")
2069
2070 bot_tests = self.flatten_tests_for_bot(bot_info)
2071 return self.output_query_result(bot_tests, args.json)
2072
2073 # For queries starting with 'tests'
2074 elif cmd_class == "tests":
2075 if not len(query) == 1 and not len(query) == 2:
2076 self.error_msg("The query should have 0 or 1 '/', found %s instead."
2077 % str(len(query)-1))
2078 flattened_tests = self.flatten_tests_for_query(tests)
2079 if len(query) == 1:
2080 return self.output_query_result(flattened_tests, args.json)
2081
2082 # create params dict
2083 params = query[1].split('&')
2084 params_dict = self.parse_query_filter_params(params)
2085 matching_bots = self.find_tests_with_params(flattened_tests, params_dict)
2086 return self.output_query_result(matching_bots)
2087
2088 # For queries starting with 'test'
2089 elif cmd_class == "test":
2090 if not len(query) == 2 and not len(query) == 3:
2091 self.error_msg("The query should have 1 or 2 '/', found %s instead."
2092 % str(len(query)-1))
2093 test_id = query[1]
2094 if len(query) == 2:
2095 flattened_tests = self.flatten_tests_for_query(tests)
2096 for test in flattened_tests:
2097 if test == test_id:
2098 return self.output_query_result(flattened_tests[test], args.json)
2099 self.error_msg("There is no test named %s." % test_id)
2100 if not query[2] == 'bots':
2101 self.error_msg("The query should be in the format: " +
2102 "test/<test-name>/bots")
2103 bots_for_test = self.find_bots_that_run_test(test_id, bots)
2104 return self.output_query_result(bots_for_test)
2105
2106 else:
2107 self.error_msg("Your command did not match any valid commands." +
2108 "Try starting with 'bots', 'bot', 'tests', or 'test'.")
Kenneth Russelleb60cbd22017-12-05 07:54:282109
Garrett Beaty1afaccc2020-06-25 19:58:152110 def main(self): # pragma: no cover
Kenneth Russelleb60cbd22017-12-05 07:54:282111 if self.args.check:
Stephen Martinis7eb8b612018-09-21 00:17:502112 self.check_consistency(verbose=self.args.verbose)
Karen Qiane24b7ee2019-02-12 23:37:062113 elif self.args.query:
2114 self.query(self.args)
Kenneth Russelleb60cbd22017-12-05 07:54:282115 else:
Greg Gutermanf60eb052020-03-12 17:40:012116 self.write_json_result(self.generate_outputs())
Kenneth Russelleb60cbd22017-12-05 07:54:282117 return 0
2118
2119if __name__ == "__main__": # pragma: no cover
Garrett Beaty1afaccc2020-06-25 19:58:152120 generator = BBJSONGenerator(BBJSONGenerator.parse_args(sys.argv[1:]))
2121 sys.exit(generator.main())