run_variations_smoke_tests.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. #!/usr/bin/env vpython3
  2. # Copyright 2021 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. """A smoke test to verify Chrome doesn't crash and basic rendering is functional
  6. when parsing a newly given variations seed.
  7. """
  8. import argparse
  9. import http
  10. import json
  11. import logging
  12. import os
  13. import shutil
  14. from struct import pack
  15. import subprocess
  16. import sys
  17. import tempfile
  18. import time
  19. from functools import partial
  20. from http.server import SimpleHTTPRequestHandler
  21. from pkg_resources import packaging
  22. from threading import Thread
  23. import pkg_resources
  24. from skia_gold_infra.finch_skia_gold_properties import FinchSkiaGoldProperties
  25. from skia_gold_infra import finch_skia_gold_utils
  26. import variations_seed_access_helper as seed_helper
  27. _THIS_DIR = os.path.abspath(os.path.dirname(__file__))
  28. _VARIATIONS_TEST_DATA = 'variations_smoke_test_data'
  29. _VERSION_STRING = 'PRODUCT_VERSION'
  30. _FLAG_RELEASE_VERSION = packaging.version.parse('105.0.5176.3')
  31. # Add src/testing/ into sys.path for importing common without pylint errors.
  32. sys.path.append(
  33. os.path.abspath(os.path.join(os.path.dirname(__file__), os.path.pardir)))
  34. from scripts import common
  35. from selenium import webdriver
  36. from selenium.webdriver import ChromeOptions
  37. from selenium.common.exceptions import NoSuchElementException
  38. from selenium.common.exceptions import WebDriverException
  39. # Constants for the waiting for seed from finch server
  40. _MAX_ATTEMPTS = 2
  41. _WAIT_TIMEOUT_IN_SEC = 0.5
  42. # Test cases to verify web elements can be rendered correctly.
  43. _TEST_CASES = [
  44. {
  45. # data:text/html,<h1 id="success">Success</h1>
  46. 'url': 'data:text/html,%3Ch1%20id%3D%22success%22%3ESuccess%3C%2Fh1%3E',
  47. 'expected_id': 'success',
  48. 'expected_text': 'Success',
  49. },
  50. {
  51. 'url': 'http://localhost:8000',
  52. 'expected_id': 'sites-chrome-userheader-title',
  53. 'expected_text': 'The Chromium Projects',
  54. 'skia_gold_image': 'finch_smoke_render_chromium_org_html',
  55. },
  56. ]
  57. def _get_httpd():
  58. """Returns a HTTPServer instance."""
  59. hostname = "localhost"
  60. port = 8000
  61. directory = os.path.join(_THIS_DIR, _VARIATIONS_TEST_DATA, "http_server")
  62. httpd = None
  63. handler = partial(SimpleHTTPRequestHandler, directory=directory)
  64. httpd = http.server.HTTPServer((hostname, port), handler)
  65. httpd.timeout = 0.5
  66. httpd.allow_reuse_address = True
  67. return httpd
  68. def _get_platform():
  69. """Returns the host platform.
  70. Returns:
  71. One of 'linux', 'win' and 'mac'.
  72. """
  73. if sys.platform == 'win32' or sys.platform == 'cygwin':
  74. return 'win'
  75. if sys.platform.startswith('linux'):
  76. return 'linux'
  77. if sys.platform == 'darwin':
  78. return 'mac'
  79. raise RuntimeError(
  80. 'Unsupported platform: %s. Only Linux (linux*) and Mac (darwin) and '
  81. 'Windows (win32 or cygwin) are supported' % sys.platform)
  82. def _find_chrome_binary(): #pylint: disable=inconsistent-return-statements
  83. """Finds and returns the relative path to the Chrome binary.
  84. This function assumes that the CWD is the build directory.
  85. Returns:
  86. A relative path to the Chrome binary.
  87. """
  88. platform = _get_platform()
  89. if platform == 'linux':
  90. return os.path.join('.', 'chrome')
  91. if platform == 'mac':
  92. chrome_name = 'Google Chrome'
  93. return os.path.join('.', chrome_name + '.app', 'Contents', 'MacOS',
  94. chrome_name)
  95. if platform == 'win':
  96. return os.path.join('.', 'chrome.exe')
  97. def _confirm_new_seed_downloaded(user_data_dir,
  98. path_chromedriver,
  99. chrome_options,
  100. old_seed=None,
  101. old_signature=None):
  102. """Confirms the new seed to be downloaded from finch server.
  103. Note that Local State does not dump until Chrome has exited.
  104. Args:
  105. user_data_dir: the use directory used to store fetched seed.
  106. path_chromedriver: the path of chromedriver binary.
  107. chrome_options: the chrome option used to launch Chrome.
  108. old_seed: the old seed serves as a baseline. New seed should be different.
  109. old_signature: the old signature serves as a baseline. New signature should
  110. be different.
  111. Returns:
  112. True if the new seed is downloaded, otherwise False.
  113. """
  114. driver = None
  115. attempt = 0
  116. wait_timeout_in_sec = _WAIT_TIMEOUT_IN_SEC
  117. while attempt < _MAX_ATTEMPTS:
  118. # Starts Chrome to allow it to download a seed or a seed delta.
  119. driver = webdriver.Chrome(path_chromedriver, chrome_options=chrome_options)
  120. time.sleep(5)
  121. # Exits Chrome so that Local State could be serialized to disk.
  122. driver.quit()
  123. # Checks the seed and signature.
  124. current_seed, current_signature = seed_helper.get_current_seed(
  125. user_data_dir)
  126. if current_seed != old_seed and current_signature != old_signature:
  127. return True
  128. attempt += 1
  129. time.sleep(wait_timeout_in_sec)
  130. wait_timeout_in_sec *= 2
  131. return False
  132. def _check_chrome_version():
  133. path_chrome = os.path.abspath(_find_chrome_binary())
  134. OS = _get_platform()
  135. #(crbug/158372)
  136. if OS == 'win':
  137. cmd = ('powershell -command "&{(Get-Item'
  138. '\''+ path_chrome + '\').VersionInfo.ProductVersion}"')
  139. version = subprocess.run(cmd, check=True,
  140. capture_output=True).stdout.decode('utf-8')
  141. else:
  142. cmd = [path_chrome, '--version']
  143. version = subprocess.run(cmd, check=True,
  144. capture_output=True).stdout.decode('utf-8')
  145. #only return the version number portion
  146. version = version.strip().split(" ")[-1]
  147. return packaging.version.parse(version)
  148. def _inject_seed(user_data_dir, path_chromedriver, chrome_options):
  149. # Verify a production version of variations seed was fetched successfully.
  150. if not _confirm_new_seed_downloaded(user_data_dir, path_chromedriver,
  151. chrome_options):
  152. logging.error('Failed to fetch variations seed on initial run')
  153. # For MacOS, there is sometime the test fail to download seed on initial
  154. # run (crbug/1312393)
  155. if _get_platform() != 'mac':
  156. return 1
  157. # Inject the test seed.
  158. # This is a path as fallback when |seed_helper.load_test_seed_from_file()|
  159. # can't find one under src root.
  160. hardcoded_seed_path = os.path.join(_THIS_DIR, _VARIATIONS_TEST_DATA,
  161. 'variations_seed_beta_%s.json' % _get_platform())
  162. seed, signature = seed_helper.load_test_seed_from_file(hardcoded_seed_path)
  163. if not seed or not signature:
  164. logging.error(
  165. 'Ill-formed test seed json file: "%s" and "%s" are required',
  166. seed_helper.LOCAL_STATE_SEED_NAME,
  167. seed_helper.LOCAL_STATE_SEED_SIGNATURE_NAME)
  168. return 1
  169. if not seed_helper.inject_test_seed(seed, signature, user_data_dir):
  170. logging.error('Failed to inject the test seed')
  171. return 1
  172. return 0
  173. def _run_tests(work_dir, skia_util, *args):
  174. """Runs the smoke tests.
  175. Args:
  176. work_dir: A working directory to store screenshots and other artifacts.
  177. skia_util: A FinchSkiaGoldUtil used to do pixel test.
  178. args: Arguments to be passed to the chrome binary.
  179. Returns:
  180. 0 if tests passed, otherwise 1.
  181. """
  182. skia_gold_session = skia_util.SkiaGoldSession
  183. path_chrome = _find_chrome_binary()
  184. path_chromedriver = os.path.join('.', 'chromedriver')
  185. hardcoded_seed_path = os.path.join(_THIS_DIR, _VARIATIONS_TEST_DATA,
  186. 'variations_seed_beta_%s.json' % _get_platform())
  187. path_seed = seed_helper.get_test_seed_file_path(hardcoded_seed_path)
  188. user_data_dir = tempfile.mkdtemp()
  189. _, log_file = tempfile.mkstemp()
  190. chrome_options = ChromeOptions()
  191. chrome_options.binary_location = path_chrome
  192. chrome_options.add_argument('user-data-dir=' + user_data_dir)
  193. chrome_options.add_argument('log-file=' + log_file)
  194. chrome_options.add_argument('variations-test-seed-path=' + path_seed)
  195. #TODO(crbug/1342057): Remove this line.
  196. chrome_options.add_argument("disable-field-trial-config")
  197. for arg in args:
  198. chrome_options.add_argument(arg)
  199. # By default, ChromeDriver passes in --disable-backgroud-networking, however,
  200. # fetching variations seeds requires network connection, so override it.
  201. chrome_options.add_experimental_option('excludeSwitches',
  202. ['disable-background-networking'])
  203. driver = None
  204. try:
  205. chrome_verison = _check_chrome_version()
  206. # If --variations-test-seed-path flag was not implemented in this version
  207. if chrome_verison <= _FLAG_RELEASE_VERSION:
  208. if _inject_seed(user_data_dir, path_chromedriver, chrome_options) == 1:
  209. return 1
  210. # Starts Chrome with the test seed injected.
  211. driver = webdriver.Chrome(path_chromedriver, chrome_options=chrome_options)
  212. # Run test cases: visit urls and verify certain web elements are rendered
  213. # correctly.
  214. # TODO(crbug.com/1234404): Investigate pixel/layout based testing instead of
  215. # DOM based testing to verify that rendering is working properly.
  216. for t in _TEST_CASES:
  217. driver.get(t['url'])
  218. driver.set_window_size(1280, 1024)
  219. element = driver.find_element_by_id(t['expected_id'])
  220. if not element.is_displayed() or t['expected_text'] != element.text:
  221. logging.error(
  222. 'Test failed because element: "%s" is not visibly found after '
  223. 'visiting url: "%s"', t['expected_text'], t['url'])
  224. return 1
  225. if 'skia_gold_image' in t:
  226. image_name = t['skia_gold_image']
  227. sc_file = os.path.join(work_dir, image_name + '.png')
  228. driver.find_element_by_id('body').screenshot(sc_file)
  229. force_dryrun = False
  230. if skia_util.IsTryjobRun and skia_util.IsRetryWithoutPatch:
  231. force_dryrun = True
  232. status, error = skia_gold_session.RunComparison(
  233. name=image_name, png_file=sc_file, force_dryrun=force_dryrun)
  234. if status:
  235. finch_skia_gold_utils.log_skia_gold_status_code(
  236. skia_gold_session, image_name, status, error)
  237. return status
  238. driver.quit()
  239. except WebDriverException as e:
  240. logging.error('Chrome exited abnormally, likely due to a crash.\n%s', e)
  241. return 1
  242. except NoSuchElementException as e:
  243. logging.error('Failed to find the expected web element.\n%s', e)
  244. return 1
  245. finally:
  246. shutil.rmtree(user_data_dir, ignore_errors=True)
  247. # Print logs for debugging purpose.
  248. with open(log_file) as f:
  249. logging.info('Chrome logs for debugging:\n%s', f.read())
  250. shutil.rmtree(log_file, ignore_errors=True)
  251. if driver:
  252. driver.quit()
  253. return 0
  254. def _start_local_http_server():
  255. """Starts a local http server.
  256. Returns:
  257. A local http.server.HTTPServer.
  258. """
  259. httpd = _get_httpd()
  260. thread = None
  261. address = "http://{}:{}".format(httpd.server_name, httpd.server_port)
  262. logging.info("%s is used as local http server.", address)
  263. thread = Thread(target=httpd.serve_forever)
  264. thread.setDaemon(True)
  265. thread.start()
  266. return httpd
  267. def main_run(args):
  268. """Runs the variations smoke tests."""
  269. logging.basicConfig(level=logging.INFO)
  270. parser = argparse.ArgumentParser()
  271. parser.add_argument('--isolated-script-test-output', type=str)
  272. parser.add_argument('--isolated-script-test-filter', type=str)
  273. FinchSkiaGoldProperties.AddCommandLineArguments(parser)
  274. args, rest = parser.parse_known_args()
  275. temp_dir = tempfile.mkdtemp()
  276. httpd = _start_local_http_server()
  277. skia_util = finch_skia_gold_utils.FinchSkiaGoldUtil(
  278. temp_dir, args)
  279. try:
  280. rc = _run_tests(temp_dir, skia_util, *rest)
  281. if args.isolated_script_test_output:
  282. with open(args.isolated_script_test_output, 'w') as f:
  283. common.record_local_script_results('run_variations_smoke_tests', f, [],
  284. rc == 0)
  285. finally:
  286. httpd.shutdown()
  287. shutil.rmtree(temp_dir, ignore_errors=True)
  288. return rc
  289. def main_compile_targets(args):
  290. """Returns the list of targets to compile in order to run this test."""
  291. json.dump(['chrome', 'chromedriver'], args.output)
  292. return 0
  293. if __name__ == '__main__':
  294. if 'compile_targets' in sys.argv:
  295. funcs = {
  296. 'run': None,
  297. 'compile_targets': main_compile_targets,
  298. }
  299. sys.exit(common.run_script(sys.argv[1:], funcs))
  300. sys.exit(main_run(sys.argv[1:]))