Hash :
f30cfd18
Author :
Date :
2022-08-16T16:50:33
Perf and gold tests detect test SKIPs from json results. Make angle_test_util.RunTestSuite() gets and returns json results (using --isolated-script-test-output). perf tests has an additional special case (filed https://anglebug.com/7578): Previously when metrics were missing it was assumed that this was due to tests being skipped - which seems to currently be the case except for the special case of GLMark2Benchmark* tests. Those produce .fps/.score metrics instead of the metrics expected by this script. This CL keeps those tests running (once) but then marks them as SKIP in test results when no metrics are found (which is the behavior before this CL; it might actually make more sense to count this as PASS because everything matches our expectations). We're still running them once, so if they FAIL we'll get notified. gold tests: Use json results file instead of checking for '[ SKIPPED ]' in stdout. Bug: angleproject:7299 Bug: angleproject:7578 Change-Id: Ia751784ad1aa94dc855c8b58ebfe5ba3e06e462f Reviewed-on: https://chromium-review.googlesource.com/c/angle/angle/+/3826167 Reviewed-by: Amirali Abdolrashidi <abdolrashidi@google.com> Commit-Queue: Roman Lavrov <romanl@google.com>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415
# Copyright 2022 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import functools
import glob
import hashlib
import json
import logging
import os
import pathlib
import posixpath
import random
import re
import subprocess
import tarfile
import tempfile
import threading
import time
import angle_path_util
class _Global(object):
initialized = False
is_android = False
current_suite = None
def _ApkPath(suite_name):
return os.path.join('%s_apk' % suite_name, '%s-debug.apk' % suite_name)
def Initialize(suite_name):
if _Global.initialized:
return
if os.path.exists(_ApkPath(suite_name)):
_Global.is_android = True
_GetAdbRoot()
_Global.initialized = True
def IsAndroid():
assert _Global.initialized, 'Initialize not called'
return _Global.is_android
def _EnsureTestSuite(suite_name):
assert IsAndroid()
if _Global.current_suite != suite_name:
_PrepareTestSuite(suite_name)
_Global.current_suite = suite_name
def _Run(cmd):
logging.debug('Executing command: %s', cmd)
startupinfo = None
if hasattr(subprocess, 'STARTUPINFO'):
# Prevent console window popping up on Windows
startupinfo = subprocess.STARTUPINFO()
startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
startupinfo.wShowWindow = subprocess.SW_HIDE
output = subprocess.check_output(cmd, startupinfo=startupinfo)
return output
@functools.lru_cache()
def _FindAdb():
platform_tools = (
pathlib.Path(angle_path_util.ANGLE_ROOT_DIR) / 'third_party' / 'android_sdk' / 'public' /
'platform-tools')
if platform_tools.exists():
adb = str(platform_tools / 'adb')
else:
adb = 'adb'
adb_info = subprocess.check_output([adb, '--version']).decode()
logging.info('adb --version: %s', adb_info)
return adb
def _AdbRun(args):
return _Run([_FindAdb()] + args)
def _AdbShell(cmd):
return _Run([_FindAdb(), 'shell', cmd])
def _GetAdbRoot():
_AdbRun(['root'])
for _ in range(20):
time.sleep(0.5)
try:
id_out = _AdbShell('id').decode('ascii')
if 'uid=0(root)' in id_out:
return
except Exception:
continue
raise Exception("adb root failed")
def _ReadDeviceFile(device_path):
with _TempLocalFile() as tempfile_path:
_AdbRun(['pull', device_path, tempfile_path])
with open(tempfile_path, 'rb') as f:
return f.read()
def _RemoveDeviceFile(device_path):
_AdbShell('rm -f ' + device_path + ' || true') # ignore errors
def _AddRestrictedTracesJson():
def add(tar, fn):
assert (fn.startswith('../../'))
tar.add(fn, arcname=fn.replace('../../', ''))
with _TempLocalFile() as tempfile_path:
with tarfile.open(tempfile_path, 'w', format=tarfile.GNU_FORMAT) as tar:
for f in glob.glob('../../src/tests/restricted_traces/*/*.json', recursive=True):
add(tar, f)
add(tar, '../../src/tests/restricted_traces/restricted_traces.json')
_AdbRun(['push', tempfile_path, '/sdcard/chromium_tests_root/t.tar'])
_AdbShell('r=/sdcard/chromium_tests_root; tar -xf $r/t.tar -C $r/ && rm $r/t.tar')
def _PrepareTestSuite(suite_name):
apk_path = _ApkPath(suite_name)
logging.info('Installing apk path=%s size=%s' % (apk_path, os.path.getsize(apk_path)))
_AdbRun(['install', '-r', '-d', apk_path])
permissions = [
'android.permission.CAMERA', 'android.permission.CHANGE_CONFIGURATION',
'android.permission.READ_EXTERNAL_STORAGE', 'android.permission.RECORD_AUDIO',
'android.permission.WRITE_EXTERNAL_STORAGE'
]
_AdbShell('p=com.android.angle.test;'
'for q in %s;do pm grant "$p" "$q";done;' % ' '.join(permissions))
_AdbShell('appops set com.android.angle.test MANAGE_EXTERNAL_STORAGE allow || true')
_AdbShell('mkdir -p /sdcard/chromium_tests_root/')
if suite_name == 'angle_perftests':
_AddRestrictedTracesJson()
if suite_name == 'angle_end2end_tests':
_AdbRun([
'push', '../../src/tests/angle_end2end_tests_expectations.txt',
'/sdcard/chromium_tests_root/src/tests/angle_end2end_tests_expectations.txt'
])
def _CompareHashes(local_path, device_path):
device_hash = _AdbShell('sha256sum -b ' + device_path +
' 2> /dev/null || true').decode().strip()
if not device_hash:
return False # file not on device
h = hashlib.sha256()
with open(local_path, 'rb') as f:
for data in iter(lambda: f.read(65536), b''):
h.update(data)
return h.hexdigest() == device_hash
def PrepareRestrictedTraces(traces, check_hash=False):
start = time.time()
total_size = 0
skipped = 0
for trace in traces:
path_from_root = 'src/tests/restricted_traces/' + trace + '/' + trace + '.angledata.gz'
local_path = '../../' + path_from_root
device_path = '/sdcard/chromium_tests_root/' + path_from_root
if check_hash and _CompareHashes(local_path, device_path):
skipped += 1
else:
total_size += os.path.getsize(local_path)
_AdbRun(['push', local_path, device_path])
logging.info('Synced %d trace files (%.1fMB, %d files already ok) in %.1fs', len(traces),
total_size / 1e6, skipped,
time.time() - start)
def _RandomHex():
return hex(random.randint(0, 2**64))[2:]
@contextlib.contextmanager
def _TempDeviceDir():
path = '/sdcard/Download/temp_dir-%s' % _RandomHex()
_AdbShell('mkdir -p ' + path)
try:
yield path
finally:
_AdbShell('rm -rf ' + path)
@contextlib.contextmanager
def _TempDeviceFile():
path = '/sdcard/Download/temp_file-%s' % _RandomHex()
try:
yield path
finally:
_AdbShell('rm -f ' + path)
@contextlib.contextmanager
def _TempLocalFile():
fd, path = tempfile.mkstemp()
os.close(fd)
try:
yield path
finally:
os.remove(path)
def _RunInstrumentation(flags):
with _TempDeviceFile() as temp_device_file:
cmd = ' '.join([
'p=com.android.angle.test;',
'ntr=org.chromium.native_test.NativeTestInstrumentationTestRunner;',
'am instrument -w',
'-e $ntr.NativeTestActivity "$p".AngleUnitTestActivity',
'-e $ntr.ShardNanoTimeout 2400000000000',
'-e org.chromium.native_test.NativeTest.CommandLineFlags "%s"' % ' '.join(flags),
'-e $ntr.StdoutFile ' + temp_device_file,
'"$p"/org.chromium.build.gtest_apk.NativeTestInstrumentationTestRunner',
])
_AdbShell(cmd)
return _ReadDeviceFile(temp_device_file)
def _DumpDebugInfo(since_time):
logcat_output = _AdbRun(['logcat', '-t', since_time]).decode()
logging.info('logcat:\n%s', logcat_output)
pid_lines = [
ln for ln in logcat_output.split('\n')
if 'org.chromium.native_test.NativeTest.StdoutFile' in ln
]
if pid_lines:
debuggerd_output = _AdbShell('debuggerd %s' % pid_lines[-1].split(' ')[2]).decode()
logging.warning('debuggerd output:\n%s', debuggerd_output)
def _RunInstrumentationWithTimeout(flags, timeout):
initial_time = _AdbShell('date +"%F %T.%3N"').decode().strip()
results = []
def run():
results.append(_RunInstrumentation(flags))
t = threading.Thread(target=run)
t.daemon = True
t.start()
t.join(timeout=timeout)
if t.is_alive(): # join timed out
logging.warning('Timed out, dumping debug info')
_DumpDebugInfo(since_time=initial_time)
raise TimeoutError('Test run did not finish in %s seconds' % timeout)
return results[0]
def AngleSystemInfo(args):
_EnsureTestSuite('angle_system_info_test')
with _TempDeviceDir() as temp_dir:
_RunInstrumentation(args + ['--render-test-output-dir=' + temp_dir])
output_file = posixpath.join(temp_dir, 'angle_system_info.json')
return json.loads(_ReadDeviceFile(output_file))
def ListTests(suite_name):
_EnsureTestSuite(suite_name)
out_lines = _RunInstrumentation(["--list-tests"]).decode('ascii').split('\n')
start = out_lines.index('Tests list:')
end = out_lines.index('End tests list.')
return out_lines[start + 1:end]
def _PullDir(device_dir, local_dir):
files = _AdbShell('ls -1 %s' % device_dir).decode('ascii').split('\n')
for f in files:
f = f.strip()
if f:
_AdbRun(['pull', posixpath.join(device_dir, f), posixpath.join(local_dir, f)])
def _RemoveFlag(args, f):
matches = [a for a in args if a.startswith(f + '=')]
assert len(matches) <= 1
if matches:
original_value = matches[0].split('=')[1]
args.remove(matches[0])
else:
original_value = None
return original_value
def RunSmokeTest():
_EnsureTestSuite('angle_perftests')
test_name = 'TracePerfTest.Run/vulkan_words_with_friends_2'
run_instrumentation_timeout = 60
logging.info('Running smoke test (%s)', test_name)
PrepareRestrictedTraces([GetTraceFromTestName(test_name)])
with _TempDeviceFile() as device_test_output_path:
flags = [
'--gtest_filter=' + test_name, '--no-warmup', '--steps-per-trial', '1', '--trials',
'1', '--isolated-script-test-output=' + device_test_output_path
]
try:
_RunInstrumentationWithTimeout(flags, run_instrumentation_timeout)
except TimeoutError:
raise Exception('Smoke test did not finish in %s seconds' %
run_instrumentation_timeout)
test_output = _ReadDeviceFile(device_test_output_path)
output_json = json.loads(test_output)
if output_json['tests'][test_name]['actual'] != 'PASS':
raise Exception('Smoke test (%s) failed' % test_name)
logging.info('Smoke test passed')
def RunTests(test_suite, args, stdoutfile=None, log_output=True):
_EnsureTestSuite(test_suite)
args = args[:]
test_output_path = _RemoveFlag(args, '--isolated-script-test-output')
perf_output_path = _RemoveFlag(args, '--isolated-script-test-perf-output')
test_output_dir = _RemoveFlag(args, '--render-test-output-dir')
result = 0
output = b''
output_json = {}
try:
with contextlib.ExitStack() as stack:
device_test_output_path = stack.enter_context(_TempDeviceFile())
args.append('--isolated-script-test-output=' + device_test_output_path)
if perf_output_path:
device_perf_path = stack.enter_context(_TempDeviceFile())
args.append('--isolated-script-test-perf-output=%s' % device_perf_path)
if test_output_dir:
device_output_dir = stack.enter_context(_TempDeviceDir())
args.append('--render-test-output-dir=' + device_output_dir)
output = _RunInstrumentationWithTimeout(args, timeout=10 * 60)
test_output = _ReadDeviceFile(device_test_output_path)
if test_output_path:
with open(test_output_path, 'wb') as f:
f.write(test_output)
output_json = json.loads(test_output)
num_failures = output_json.get('num_failures_by_type', {}).get('FAIL', 0)
interrupted = output_json.get('interrupted', True) # Normally set to False
if num_failures != 0 or interrupted or output_json.get('is_unexpected', False):
logging.error('Tests failed: %s', test_output.decode())
result = 1
if test_output_dir:
_PullDir(device_output_dir, test_output_dir)
if perf_output_path:
_AdbRun(['pull', device_perf_path, perf_output_path])
if log_output:
logging.info(output.decode())
if stdoutfile:
with open(stdoutfile, 'wb') as f:
f.write(output)
except Exception as e:
logging.exception(e)
result = 1
return result, output, output_json
def GetTraceFromTestName(test_name):
m = re.search(r'TracePerfTest.Run/(native|vulkan)_(.*)', test_name)
if m:
return m.group(2)
if test_name.startswith('TracePerfTest.Run/'):
raise Exception('Unexpected test: %s' % test_name)
return None