Path: blob/main_old/src/tests/restricted_traces/restricted_trace_gold_tests.py
1693 views
#! /usr/bin/env vpython1#2# [VPYTHON:BEGIN]3# wheel: <4# name: "infra/python/wheels/psutil/${vpython_platform}"5# version: "version:5.2.2"6# >7# wheel: <8# name: "infra/python/wheels/six-py2_py3"9# version: "version:1.10.0"10# >11# [VPYTHON:END]12#13# Copyright 2020 The ANGLE Project Authors. All rights reserved.14# Use of this source code is governed by a BSD-style license that can be15# found in the LICENSE file.16#17# restricted_trace_gold_tests.py:18# Uses Skia Gold (https://skia.org/dev/testing/skiagold) to run pixel tests with ANGLE traces.19#20# Requires vpython to run standalone. Run with --help for usage instructions.2122import argparse23import contextlib24import fnmatch25import json26import logging27import os28import platform29import re30import shutil31import sys32import tempfile33import time34import traceback3536# Add //src/testing into sys.path for importing xvfb and test_env, and37# //src/testing/scripts for importing common.38d = os.path.dirname39THIS_DIR = d(os.path.abspath(__file__))40sys.path.insert(0, d(THIS_DIR))4142from skia_gold import angle_skia_gold_properties43from skia_gold import angle_skia_gold_session_manager4445ANGLE_SRC_DIR = d(d(d(THIS_DIR)))46sys.path.insert(0, os.path.join(ANGLE_SRC_DIR, 'testing'))47sys.path.insert(0, os.path.join(ANGLE_SRC_DIR, 'testing', 'scripts'))48# Handle the Chromium-relative directory as well. As long as one directory49# is valid, Python is happy.50CHROMIUM_SRC_DIR = d(d(ANGLE_SRC_DIR))51sys.path.insert(0, os.path.join(CHROMIUM_SRC_DIR, 'testing'))52sys.path.insert(0, os.path.join(CHROMIUM_SRC_DIR, 'testing', 'scripts'))5354import common55import test_env56import xvfb575859def IsWindows():60return sys.platform == 'cygwin' or sys.platform.startswith('win')616263DEFAULT_TEST_SUITE = 'angle_perftests'64DEFAULT_TEST_PREFIX = 'TracePerfTest.Run/vulkan_'65DEFAULT_SCREENSHOT_PREFIX = 'angle_vulkan_'66DEFAULT_BATCH_SIZE = 567DEFAULT_LOG = 'info'6869# Filters out stuff like: " I 72.572s run_tests_on_device(96071FFAZ00096) "70ANDROID_LOGGING_PREFIX = r'I +\d+.\d+s \w+\(\w+\) '71ANDROID_BEGIN_SYSTEM_INFO = '>>ScopedMainEntryLogger'7273# Test expectations74FAIL = 'FAIL'75PASS = 'PASS'76SKIP = 'SKIP'777879@contextlib.contextmanager80def temporary_dir(prefix=''):81path = tempfile.mkdtemp(prefix=prefix)82try:83yield path84finally:85logging.info("Removing temporary directory: %s" % path)86shutil.rmtree(path)878889def add_skia_gold_args(parser):90group = parser.add_argument_group('Skia Gold Arguments')91group.add_argument('--git-revision', help='Revision being tested.', default=None)92group.add_argument(93'--gerrit-issue', help='For Skia Gold integration. Gerrit issue ID.', default='')94group.add_argument(95'--gerrit-patchset',96help='For Skia Gold integration. Gerrit patch set number.',97default='')98group.add_argument(99'--buildbucket-id', help='For Skia Gold integration. Buildbucket build ID.', default='')100group.add_argument(101'--bypass-skia-gold-functionality',102action='store_true',103default=False,104help='Bypass all interaction with Skia Gold, effectively disabling the '105'image comparison portion of any tests that use Gold. Only meant to '106'be used in case a Gold outage occurs and cannot be fixed quickly.')107local_group = group.add_mutually_exclusive_group()108local_group.add_argument(109'--local-pixel-tests',110action='store_true',111default=None,112help='Specifies to run the test harness in local run mode or not. When '113'run in local mode, uploading to Gold is disabled and links to '114'help with local debugging are output. Running in local mode also '115'implies --no-luci-auth. If both this and --no-local-pixel-tests are '116'left unset, the test harness will attempt to detect whether it is '117'running on a workstation or not and set this option accordingly.')118local_group.add_argument(119'--no-local-pixel-tests',120action='store_false',121dest='local_pixel_tests',122help='Specifies to run the test harness in non-local (bot) mode. When '123'run in this mode, data is actually uploaded to Gold and triage links '124'arge generated. If both this and --local-pixel-tests are left unset, '125'the test harness will attempt to detect whether it is running on a '126'workstation or not and set this option accordingly.')127group.add_argument(128'--no-luci-auth',129action='store_true',130default=False,131help='Don\'t use the service account provided by LUCI for '132'authentication for Skia Gold, instead relying on gsutil to be '133'pre-authenticated. Meant for testing locally instead of on the bots.')134135136def run_wrapper(args, cmd, env, stdoutfile=None):137if args.xvfb:138return xvfb.run_executable(cmd, env, stdoutfile=stdoutfile)139else:140return test_env.run_command_with_output(cmd, env=env, stdoutfile=stdoutfile)141142143def to_hex(num):144return hex(int(num))145146147def to_hex_or_none(num):148return 'None' if num == None else to_hex(num)149150151def to_non_empty_string_or_none(val):152return 'None' if val == '' else str(val)153154155def to_non_empty_string_or_none_dict(d, key):156return 'None' if not key in d else to_non_empty_string_or_none(d[key])157158159def get_binary_name(binary):160if IsWindows():161return '.\\%s.exe' % binary162else:163return './%s' % binary164165166def get_skia_gold_keys(args, env):167"""Get all the JSON metadata that will be passed to golctl."""168# All values need to be strings, otherwise goldctl fails.169170# Only call this method one time171if hasattr(get_skia_gold_keys, 'called') and get_skia_gold_keys.called:172logging.exception('get_skia_gold_keys may only be called once')173get_skia_gold_keys.called = True174175class Filter:176177def __init__(self):178self.accepting_lines = True179self.done_accepting_lines = False180self.android_prefix = re.compile(ANDROID_LOGGING_PREFIX)181self.lines = []182self.is_android = False183184def append(self, line):185if self.done_accepting_lines:186return187if 'Additional test environment' in line or 'android/test_runner.py' in line:188self.accepting_lines = False189self.is_android = True190if ANDROID_BEGIN_SYSTEM_INFO in line:191self.accepting_lines = True192return193if not self.accepting_lines:194return195196if self.is_android:197line = self.android_prefix.sub('', line)198199if line[0] == '}':200self.done_accepting_lines = True201202self.lines.append(line)203204def get(self):205return self.lines206207with common.temporary_file() as tempfile_path:208binary = get_binary_name('angle_system_info_test')209if run_wrapper(args, [binary, '--vulkan', '-v'], env, tempfile_path):210raise Exception('Error getting system info.')211212filter = Filter()213214with open(tempfile_path) as f:215for line in f:216filter.append(line)217218str = ''.join(filter.get())219logging.info(str)220json_data = json.loads(str)221222if len(json_data.get('gpus', [])) == 0 or not 'activeGPUIndex' in json_data:223raise Exception('Error getting system info.')224225active_gpu = json_data['gpus'][json_data['activeGPUIndex']]226227angle_keys = {228'vendor_id': to_hex_or_none(active_gpu['vendorId']),229'device_id': to_hex_or_none(active_gpu['deviceId']),230'model_name': to_non_empty_string_or_none_dict(active_gpu, 'machineModelVersion'),231'manufacturer_name': to_non_empty_string_or_none_dict(active_gpu, 'machineManufacturer'),232'os': to_non_empty_string_or_none(platform.system()),233'os_version': to_non_empty_string_or_none(platform.version()),234'driver_version': to_non_empty_string_or_none_dict(active_gpu, 'driverVersion'),235'driver_vendor': to_non_empty_string_or_none_dict(active_gpu, 'driverVendor'),236}237238return angle_keys239240241def output_diff_local_files(gold_session, image_name):242"""Logs the local diff image files from the given SkiaGoldSession.243244Args:245gold_session: A skia_gold_session.SkiaGoldSession instance to pull files246from.247image_name: A string containing the name of the image/test that was248compared.249"""250given_file = gold_session.GetGivenImageLink(image_name)251closest_file = gold_session.GetClosestImageLink(image_name)252diff_file = gold_session.GetDiffImageLink(image_name)253failure_message = 'Unable to retrieve link'254logging.error('Generated image: %s', given_file or failure_message)255logging.error('Closest image: %s', closest_file or failure_message)256logging.error('Diff image: %s', diff_file or failure_message)257258259def upload_test_result_to_skia_gold(args, gold_session_manager, gold_session, gold_properties,260screenshot_dir, image_name, artifacts):261"""Compares the given image using Skia Gold and uploads the result.262263No uploading is done if the test is being run in local run mode. Compares264the given screenshot to baselines provided by Gold, raising an Exception if265a match is not found.266267Args:268args: Command line options.269gold_session_manager: Skia Gold session manager.270gold_session: Skia Gold session.271gold_properties: Skia Gold properties.272screenshot_dir: directory where the test stores screenshots.273image_name: the name of the image being checked.274artifacts: dictionary of JSON artifacts to pass to the result merger.275"""276277use_luci = not (gold_properties.local_pixel_tests or gold_properties.no_luci_auth)278279# Note: this would be better done by iterating the screenshot directory.280png_file_name = os.path.join(screenshot_dir, DEFAULT_SCREENSHOT_PREFIX + image_name + '.png')281282if not os.path.isfile(png_file_name):283logging.info('Screenshot not found, test skipped.')284return SKIP285286status, error = gold_session.RunComparison(287name=image_name, png_file=png_file_name, use_luci=use_luci)288289artifact_name = os.path.basename(png_file_name)290artifacts[artifact_name] = [artifact_name]291292if not status:293return PASS294295status_codes = gold_session_manager.GetSessionClass().StatusCodes296if status == status_codes.AUTH_FAILURE:297logging.error('Gold authentication failed with output %s', error)298elif status == status_codes.INIT_FAILURE:299logging.error('Gold initialization failed with output %s', error)300elif status == status_codes.COMPARISON_FAILURE_REMOTE:301_, triage_link = gold_session.GetTriageLinks(image_name)302if not triage_link:303logging.error('Failed to get triage link for %s, raw output: %s', image_name, error)304logging.error('Reason for no triage link: %s',305gold_session.GetTriageLinkOmissionReason(image_name))306elif gold_properties.IsTryjobRun():307artifacts['triage_link_for_entire_cl'] = [triage_link]308else:309artifacts['gold_triage_link'] = [triage_link]310elif status == status_codes.COMPARISON_FAILURE_LOCAL:311logging.error('Local comparison failed. Local diff files:')312output_diff_local_files(gold_session, image_name)313elif status == status_codes.LOCAL_DIFF_FAILURE:314logging.error(315'Local comparison failed and an error occurred during diff '316'generation: %s', error)317# There might be some files, so try outputting them.318logging.error('Local diff files:')319output_diff_local_files(gold_session, image_name)320else:321logging.error('Given unhandled SkiaGoldSession StatusCode %s with error %s', status, error)322323return FAIL324325326def _get_batches(traces, batch_size):327for i in range(0, len(traces), batch_size):328yield traces[i:i + batch_size]329330331def _get_gtest_filter_for_batch(batch):332expanded = ['%s%s' % (DEFAULT_TEST_PREFIX, trace) for trace in batch]333return '--gtest_filter=%s' % ':'.join(expanded)334335336def _run_tests(args, tests, extra_flags, env, screenshot_dir, results, test_results):337keys = get_skia_gold_keys(args, env)338339with temporary_dir('angle_skia_gold_') as skia_gold_temp_dir:340gold_properties = angle_skia_gold_properties.ANGLESkiaGoldProperties(args)341gold_session_manager = angle_skia_gold_session_manager.ANGLESkiaGoldSessionManager(342skia_gold_temp_dir, gold_properties)343gold_session = gold_session_manager.GetSkiaGoldSession(keys)344345traces = [trace.split(' ')[0] for trace in tests]346347if args.isolated_script_test_filter:348filtered = []349for trace in traces:350# Apply test filter if present.351full_name = 'angle_restricted_trace_gold_tests.%s' % trace352if not fnmatch.fnmatch(full_name, args.isolated_script_test_filter):353logging.info('Skipping test %s because it does not match filter %s' %354(full_name, args.isolated_script_test_filter))355else:356filtered += [trace]357traces = filtered358359batches = _get_batches(traces, args.batch_size)360361for batch in batches:362for iteration in range(0, args.flaky_retries + 1):363with common.temporary_file() as tempfile_path:364# This is how we signal early exit365if not batch:366logging.debug('All tests in batch completed.')367break368if iteration > 0:369logging.info('Test run failed, running retry #%d...' % iteration)370371gtest_filter = _get_gtest_filter_for_batch(batch)372cmd = [373args.test_suite,374gtest_filter,375'--render-test-output-dir=%s' % screenshot_dir,376'--one-frame-only',377'--verbose-logging',378] + extra_flags379batch_result = PASS if run_wrapper(args, cmd, env,380tempfile_path) == 0 else FAIL381382next_batch = []383for trace in batch:384artifacts = {}385386if batch_result == PASS:387logging.debug('upload test result: %s' % trace)388result = upload_test_result_to_skia_gold(args, gold_session_manager,389gold_session, gold_properties,390screenshot_dir, trace,391artifacts)392else:393result = batch_result394395expected_result = SKIP if result == SKIP else PASS396test_results[trace] = {'expected': expected_result, 'actual': result}397if len(artifacts) > 0:398test_results[trace]['artifacts'] = artifacts399if result == FAIL:400next_batch.append(trace)401batch = next_batch402403# These properties are recorded after iteration to ensure they only happen once.404for _, trace_results in test_results.items():405result = trace_results['actual']406results['num_failures_by_type'][result] += 1407if result == FAIL:408trace_results['is_unexpected'] = True409410return results['num_failures_by_type'][FAIL] == 0411412413def _shard_tests(tests, shard_count, shard_index):414return [tests[index] for index in range(shard_index, len(tests), shard_count)]415416417def main():418parser = argparse.ArgumentParser()419parser.add_argument('--isolated-script-test-output', type=str)420parser.add_argument('--isolated-script-test-perf-output', type=str)421parser.add_argument('--isolated-script-test-filter', type=str)422parser.add_argument('--test-suite', help='Test suite to run.', default=DEFAULT_TEST_SUITE)423parser.add_argument('--render-test-output-dir', help='Directory to store screenshots')424parser.add_argument('--xvfb', help='Start xvfb.', action='store_true')425parser.add_argument(426'--flaky-retries', help='Number of times to retry failed tests.', type=int, default=0)427parser.add_argument(428'--shard-count',429help='Number of shards for test splitting. Default is 1.',430type=int,431default=1)432parser.add_argument(433'--shard-index',434help='Index of the current shard for test splitting. Default is 0.',435type=int,436default=0)437parser.add_argument(438'--batch-size',439help='Number of tests to run in a group. Default: %d' % DEFAULT_BATCH_SIZE,440type=int,441default=DEFAULT_BATCH_SIZE)442parser.add_argument(443'-l', '--log', help='Log output level. Default is %s.' % DEFAULT_LOG, default=DEFAULT_LOG)444445add_skia_gold_args(parser)446447args, extra_flags = parser.parse_known_args()448logging.basicConfig(level=args.log.upper())449450env = os.environ.copy()451452if 'GTEST_TOTAL_SHARDS' in env and int(env['GTEST_TOTAL_SHARDS']) != 1:453if 'GTEST_SHARD_INDEX' not in env:454logging.error('Sharding params must be specified together.')455sys.exit(1)456args.shard_count = int(env.pop('GTEST_TOTAL_SHARDS'))457args.shard_index = int(env.pop('GTEST_SHARD_INDEX'))458459results = {460'tests': {},461'interrupted': False,462'seconds_since_epoch': time.time(),463'path_delimiter': '.',464'version': 3,465'num_failures_by_type': {466FAIL: 0,467PASS: 0,468SKIP: 0,469},470}471472test_results = {}473474rc = 0475476try:477if IsWindows():478args.test_suite = '.\\%s.exe' % args.test_suite479else:480args.test_suite = './%s' % args.test_suite481482# read test set483json_name = os.path.join(ANGLE_SRC_DIR, 'src', 'tests', 'restricted_traces',484'restricted_traces.json')485with open(json_name) as fp:486tests = json.load(fp)487488# Split tests according to sharding489sharded_tests = _shard_tests(tests['traces'], args.shard_count, args.shard_index)490491if args.render_test_output_dir:492if not _run_tests(args, sharded_tests, extra_flags, env, args.render_test_output_dir,493results, test_results):494rc = 1495elif 'ISOLATED_OUTDIR' in env:496if not _run_tests(args, sharded_tests, extra_flags, env, env['ISOLATED_OUTDIR'],497results, test_results):498rc = 1499else:500with temporary_dir('angle_trace_') as temp_dir:501if not _run_tests(args, sharded_tests, extra_flags, env, temp_dir, results,502test_results):503rc = 1504505except Exception:506traceback.print_exc()507results['interrupted'] = True508rc = 1509510if test_results:511results['tests']['angle_restricted_trace_gold_tests'] = test_results512513if args.isolated_script_test_output:514with open(args.isolated_script_test_output, 'w') as out_file:515out_file.write(json.dumps(results, indent=2))516517if args.isolated_script_test_perf_output:518with open(args.isolated_script_test_perf_output, 'w') as out_file:519out_file.write(json.dumps({}))520521return rc522523524# This is not really a "script test" so does not need to manually add525# any additional compile targets.526def main_compile_targets(args):527json.dump([], args.output)528529530if __name__ == '__main__':531# Conform minimally to the protocol defined by ScriptTest.532if 'compile_targets' in sys.argv:533funcs = {534'run': None,535'compile_targets': main_compile_targets,536}537sys.exit(common.run_script(sys.argv[1:], funcs))538sys.exit(main())539540541