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
|
#!/usr/bin/env vpython3
# Copyright 2021 The Chromium Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""A smoke test to verify Chrome doesn't crash and basic rendering is functional
when parsing a newly given variations seed.
"""
import argparse
import http
import json
import logging
import os
import shutil
import subprocess
import sys
import tempfile
import time
from functools import partial
from http.server import SimpleHTTPRequestHandler
from threading import Thread
# vpython-provided modules.
import packaging.version # pylint: disable=import-error
# //third_party/webdriver/pylib imports.
from selenium import webdriver
from selenium.webdriver import ChromeOptions
from selenium.webdriver.chrome.service import Service
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import WebDriverException
# //testing/scripts imports.
import common
import variations_seed_access_helper as seed_helper
from skia_gold_infra import finch_skia_gold_utils
_THIS_DIR = os.path.abspath(os.path.dirname(__file__))
_CHROMIUM_SRC_DIR = os.path.realpath(os.path.join(_THIS_DIR, '..', '..'))
sys.path.append(os.path.join(_CHROMIUM_SRC_DIR, 'build'))
# //build imports.
from skia_gold_common.skia_gold_properties import SkiaGoldProperties
_VARIATIONS_TEST_DATA = 'variations_smoke_test_data'
_VERSION_STRING = 'PRODUCT_VERSION'
_FLAG_RELEASE_VERSION = packaging.version.parse('105.0.5176.3')
# Constants for the waiting for seed from finch server
_MAX_ATTEMPTS = 2
_WAIT_TIMEOUT_IN_SEC = 0.5
# Test cases to verify web elements can be rendered correctly.
_TEST_CASES = [
{
# data:text/html,<h1 id="success">Success</h1>
'url': 'data:text/html,%3Ch1%20id%3D%22success%22%3ESuccess%3C%2Fh1%3E',
'expected_id': 'success',
'expected_text': 'Success',
},
{
'url': 'http://localhost:8000',
'expected_id': 'sites-chrome-userheader-title',
'expected_text': 'The Chromium Projects',
'skia_gold_image': 'finch_smoke_render_chromium_org_html',
},
]
def _get_httpd():
"""Returns a HTTPServer instance."""
hostname = 'localhost'
port = 8000
directory = os.path.join(_THIS_DIR, _VARIATIONS_TEST_DATA, 'http_server')
httpd = None
handler = partial(SimpleHTTPRequestHandler, directory=directory)
httpd = http.server.HTTPServer((hostname, port), handler)
httpd.timeout = 0.5
httpd.allow_reuse_address = True
return httpd
def _get_platform():
"""Returns the host platform.
Returns:
One of 'linux', 'win' and 'mac'.
"""
if sys.platform == 'win32' or sys.platform == 'cygwin':
return 'win'
if sys.platform.startswith('linux'):
return 'linux'
if sys.platform == 'darwin':
return 'mac'
raise RuntimeError(
'Unsupported platform: %s. Only Linux (linux*) and Mac (darwin) and '
'Windows (win32 or cygwin) are supported' % sys.platform)
def _find_chrome_binary(): #pylint: disable=inconsistent-return-statements
"""Finds and returns the relative path to the Chrome binary.
This function assumes that the CWD is the build directory.
Returns:
A relative path to the Chrome binary.
"""
platform = _get_platform()
if platform == 'linux':
return os.path.join('.', 'chrome')
if platform == 'mac':
chrome_name = 'Google Chrome'
return os.path.join('.', chrome_name + '.app', 'Contents', 'MacOS',
chrome_name)
if platform == 'win':
return os.path.join('.', 'chrome.exe')
def _confirm_new_seed_downloaded(user_data_dir,
path_chromedriver,
chrome_options,
old_seed=None,
old_signature=None):
"""Confirms the new seed to be downloaded from finch server.
Note that Local State does not dump until Chrome has exited.
Args:
user_data_dir: the use directory used to store fetched seed.
path_chromedriver: the path of chromedriver binary.
chrome_options: the chrome option used to launch Chrome.
old_seed: the old seed serves as a baseline. New seed should be different.
old_signature: the old signature serves as a baseline. New signature should
be different.
Returns:
True if the new seed is downloaded, otherwise False.
"""
driver = None
attempt = 0
wait_timeout_in_sec = _WAIT_TIMEOUT_IN_SEC
while attempt < _MAX_ATTEMPTS:
# Starts Chrome to allow it to download a seed or a seed delta.
chromedriver_service = Service(executable_path=path_chromedriver)
driver = webdriver.Chrome(service=chromedriver_service,
options=chrome_options)
time.sleep(5)
# Exits Chrome so that Local State could be serialized to disk.
driver.quit()
# Checks the seed and signature.
current_seed, current_signature = seed_helper.get_current_seed(
user_data_dir)
if current_seed != old_seed and current_signature != old_signature:
return True
attempt += 1
time.sleep(wait_timeout_in_sec)
wait_timeout_in_sec *= 2
return False
def _check_chrome_version():
path_chrome = os.path.abspath(_find_chrome_binary())
OS = _get_platform()
#(crbug/158372)
if OS == 'win':
cmd = ('powershell -command "&{(Get-Item'
"'" + path_chrome + '\').VersionInfo.ProductVersion}"')
version = subprocess.run(cmd, check=True,
capture_output=True).stdout.decode('utf-8')
else:
cmd = [path_chrome, '--version']
version = subprocess.run(cmd, check=True,
capture_output=True).stdout.decode('utf-8')
#only return the version number portion
version = version.strip().split(' ')[-1]
return packaging.version.parse(version)
def _inject_seed(user_data_dir, path_chromedriver, chrome_options):
# Verify a production version of variations seed was fetched successfully.
if not _confirm_new_seed_downloaded(user_data_dir, path_chromedriver,
chrome_options):
logging.error('Failed to fetch variations seed on initial run')
# For MacOS, there is sometime the test fail to download seed on initial
# run (crbug/1312393)
if _get_platform() != 'mac':
return 1
# Inject the test seed.
# This is a path as fallback when |seed_helper.load_test_seed_from_file()|
# can't find one under src root.
hardcoded_seed_path = os.path.join(
_THIS_DIR, _VARIATIONS_TEST_DATA,
'variations_seed_beta_%s.json' % _get_platform())
seed, signature = seed_helper.load_test_seed_from_file(hardcoded_seed_path)
if not seed or not signature:
logging.error(seed_helper.ILL_FORMED_TEST_SEED_ERROR_MESSAGE)
return 1
if not seed_helper.inject_test_seed(seed, signature, user_data_dir):
logging.error('Failed to inject the test seed')
return 1
return 0
def _run_tests(work_dir, skia_util, *args):
"""Runs the smoke tests.
Args:
work_dir: A working directory to store screenshots and other artifacts.
skia_util: A FinchSkiaGoldUtil used to do pixel test.
args: Arguments to be passed to the chrome binary.
Returns:
0 if tests passed, otherwise 1.
"""
skia_gold_session = skia_util.SkiaGoldSession
path_chrome = _find_chrome_binary()
path_chromedriver = os.path.join('.', 'chromedriver')
hardcoded_seed_path = os.path.join(
_THIS_DIR, _VARIATIONS_TEST_DATA,
'variations_seed_beta_%s.json' % _get_platform())
path_seed = seed_helper.get_test_seed_file_path(hardcoded_seed_path)
user_data_dir = tempfile.mkdtemp()
crash_dump_dir = tempfile.mkdtemp()
_, log_file = tempfile.mkstemp()
# Crashpad is a separate process and its dump locations is set via env
# variable.
os.environ['BREAKPAD_DUMP_LOCATION'] = crash_dump_dir
chrome_options = ChromeOptions()
chrome_options.binary_location = path_chrome
chrome_options.add_argument('user-data-dir=' + user_data_dir)
chrome_options.add_argument('log-file=' + log_file)
chrome_options.add_argument('variations-test-seed-path=' + path_seed)
#TODO(crbug.com/40230862): Remove this line.
chrome_options.add_argument('disable-field-trial-config')
for arg in args:
chrome_options.add_argument(arg)
# By default, ChromeDriver passes in --disable-backgroud-networking, however,
# fetching variations seeds requires network connection, so override it.
chrome_options.add_experimental_option('excludeSwitches',
['disable-background-networking'])
driver = None
try:
chrome_version = _check_chrome_version()
# If --variations-test-seed-path flag was not implemented in this version
if chrome_version <= _FLAG_RELEASE_VERSION:
if _inject_seed(user_data_dir, path_chromedriver, chrome_options) == 1:
return 1
# Starts Chrome with the test seed injected.
chromedriver_service = Service(executable_path=path_chromedriver)
driver = webdriver.Chrome(service=chromedriver_service,
options=chrome_options)
# Run test cases: visit urls and verify certain web elements are rendered
# correctly.
for t in _TEST_CASES:
driver.get(t['url'])
driver.set_window_size(1280, 1024)
element = driver.find_element(By.ID, t['expected_id'])
if not element.is_displayed() or t['expected_text'] != element.text:
logging.error(
'Test failed because element: "%s" is not visibly found after '
'visiting url: "%s"', t['expected_text'], t['url'])
return 1
if 'skia_gold_image' in t:
image_name = t['skia_gold_image']
sc_file = os.path.join(work_dir, image_name + '.png')
driver.find_element(By.ID, 'body').screenshot(sc_file)
force_dryrun = False
if skia_util.IsTryjobRun and skia_util.IsRetryWithoutPatch:
force_dryrun = True
status, error = skia_gold_session.RunComparison(
name=image_name, png_file=sc_file, force_dryrun=force_dryrun)
if status:
finch_skia_gold_utils.log_skia_gold_status_code(
skia_gold_session, image_name, status, error)
return status
driver.quit()
except NoSuchElementException as e:
logging.error('Failed to find the expected web element.\n%s', e)
return 1
except WebDriverException as e:
if os.listdir(crash_dump_dir):
logging.error('Chrome crashed and exited abnormally.\n%s', e)
else:
logging.error('Uncaught WebDriver exception thrown.\n%s', e)
return 1
finally:
shutil.rmtree(user_data_dir, ignore_errors=True)
shutil.rmtree(crash_dump_dir, ignore_errors=True)
# Print logs for debugging purpose.
with open(log_file) as f:
logging.info('Chrome logs for debugging:\n%s', f.read())
shutil.rmtree(log_file, ignore_errors=True)
if driver:
driver.quit()
return 0
def _start_local_http_server():
"""Starts a local http server.
Returns:
A local http.server.HTTPServer.
"""
httpd = _get_httpd()
thread = None
address = 'http://{}:{}'.format(httpd.server_name, httpd.server_port)
logging.info('%s is used as local http server.', address)
thread = Thread(target=httpd.serve_forever)
thread.setDaemon(True)
thread.start()
return httpd
def main_run(args):
"""Runs the variations smoke tests."""
logging.basicConfig(level=logging.INFO)
parser = argparse.ArgumentParser()
parser.add_argument('--isolated-script-test-output', type=str)
parser.add_argument('--isolated-script-test-filter', type=str)
SkiaGoldProperties.AddCommandLineArguments(parser)
args, rest = parser.parse_known_args()
temp_dir = tempfile.mkdtemp()
httpd = _start_local_http_server()
skia_util = finch_skia_gold_utils.FinchSkiaGoldUtil(temp_dir, args)
try:
rc = _run_tests(temp_dir, skia_util, *rest)
if args.isolated_script_test_output:
with open(args.isolated_script_test_output, 'w') as f:
common.record_local_script_results('run_variations_smoke_tests', f, [],
rc == 0)
finally:
httpd.shutdown()
shutil.rmtree(temp_dir, ignore_errors=True)
return rc
def main_compile_targets(args):
"""Returns the list of targets to compile in order to run this test."""
json.dump(['chrome', 'chromedriver'], args.output)
return 0
if __name__ == '__main__':
if 'compile_targets' in sys.argv:
funcs = {
'run': None,
'compile_targets': main_compile_targets,
}
sys.exit(common.run_script(sys.argv[1:], funcs))
sys.exit(main_run(sys.argv[1:]))
|