# mypy: allow-untyped-defs import os import platform import re import shutil import stat import subprocess import tempfile from abc import ABCMeta, abstractmethod from datetime import datetime, timedelta, timezone from shutil import which from typing import Optional from urllib.parse import urlsplit, quote
import html5lib import requests from packaging.specifiers import SpecifierSet
from .utils import (
call,
get,
get_download_to_descriptor,
rmtree,
sha256sum,
untar,
unzip,
) from .wpt import venv_dir
uname = platform.uname()
# The root URL for Chrome for Testing API endpoints.
CHROME_FOR_TESTING_ROOT_URL = "https://googlechromelabs.github.io/chrome-for-testing/" # File name containing a matching ChromeDriver download URL for a specific Chrome download.
CHROMEDRIVER_SAVED_DOWNLOAD_FILE = "matching_chromedriver_url.txt"
def get_ext(filename): """Get the extension from a filename with special handling for .tar.foo"""
name, ext = os.path.splitext(filename) if name.endswith(".tar"):
ext = ".tar%s" % ext return ext
def get_download_filename(resp, default=None): """Get the filename from a requests.Response, or default"""
filename = None
content_disposition = resp.headers.get("content-disposition") if content_disposition:
filenames = re.findall("filename=(.+)", content_disposition) if filenames:
filename = filenames[0]
def _get_browser_download_dir(self, dest, channel): if dest isNone: return self._get_browser_binary_dir(dest, channel)
return dest
def _get_browser_binary_dir(self, dest, channel): if dest isNone: # os.getcwd() doesn't include the venv path
dest = os.path.join(os.getcwd(), venv_dir())
dest = os.path.join(dest, "browsers", channel)
ifnot os.path.exists(dest):
os.makedirs(dest)
return dest
def download_from_url(
self, url, dest=None, channel=None, rename=None, default_name="download"
): """Download a URL into a dest/channel
:param url: The URL to download
:param dest: Directory in which to put the dowloaded
:param channel: Browser channel to append to the dest
:param rename: Optional name for the download; the original extension is preserved
:param default_name: The default name for the download ifnoneis
provided andnone can be found from the network
:return: The path to the downloaded package/installer """
self.logger.info("Downloading from %s" % url)
dest = self._get_browser_download_dir(dest, channel)
with open(output_path, "wb") as f: for chunk in resp.iter_content(chunk_size=64 * 1024):
f.write(chunk)
return output_path
@abstractmethod def download(self, dest=None, channel=None, rename=None): """Download a package or installer for the browser
:param dest: Directory in which to put the dowloaded package
:param channel: Browser channel to download
:param rename: Optional name for the downloaded package; the original
extension is preserved.
:return: The path to the downloaded package/installer """ return NotImplemented
@abstractmethod def install(self, dest=None, channel=None): """Download and install the browser.
This method usually calls download().
:param dest: Directory in which to install the browser
:param channel: Browser channel to install
:return: The path to the installed browser """ return NotImplemented
@abstractmethod def install_webdriver(self, dest=None, channel=None, browser_binary=None): """Download and install the WebDriver implementation for this browser.
:param dest: Directory in which to install the WebDriver
:param channel: Browser channel to install
:param browser_binary: The path to the browser binary
:return: The path to the installed WebDriver """ return NotImplemented
@abstractmethod def find_binary(self, venv_path=None, channel=None): """Find the binary of the browser.
If the WebDriver for the browser is able to find the binary itself, this
method doesn't need to be implemented, in which case NotImplementedError is suggested to be raised to prevent accidental use. """ return NotImplemented
@abstractmethod def find_webdriver(self, venv_path=None, channel=None): """Find the binary of the WebDriver.""" return NotImplemented
@abstractmethod def version(self, binary=None, webdriver_binary=None): """Retrieve the release version of the installed browser.""" return NotImplemented
@abstractmethod def requirements(self): """Name of the browser-specific wptrunner requirements file""" return NotImplemented
class Firefox(Browser): """Firefox-specific interface.
Includes installation, webdriver installation, and wptrunner setup methods. """
def platform_string_geckodriver(self): if self.platform isNone: raise ValueError("Unable to construct a valid Geckodriver package name for current platform")
dest = self._get_browser_binary_dir(dest, channel)
filename = os.path.basename(dest)
installer_path = self.download(dest, channel)
try:
mozinstall.install(installer_path, dest) except mozinstall.mozinstall.InstallError: if self.platform == "macos"and os.path.exists(os.path.join(dest, self.application_name.get(channel, "Firefox Nightly.app"))): # mozinstall will fail if nightly is already installed in the venv because # mac installation uses shutil.copy_tree
mozinstall.uninstall(os.path.join(dest, self.application_name.get(channel, "Firefox Nightly.app")))
mozinstall.install(filename, dest) else: raise
def get_profile_bundle_url(self, version, channel): if channel == "stable":
repo = "https://hg.mozilla.org/releases/mozilla-release"
tag = "FIREFOX_%s_RELEASE" % version.replace(".", "_") elif channel == "beta":
repo = "https://hg.mozilla.org/releases/mozilla-beta"
major_version = version.split(".", 1)[0] # For beta we have a different format for betas that are now in stable releases # vs those that are not
tags = get("https://hg.mozilla.org/releases/mozilla-beta/json-tags").json()["tags"]
tags = {item["tag"] for item in tags}
end_tag = "FIREFOX_BETA_%s_END" % major_version if end_tag in tags:
tag = end_tag else:
tag = "tip" else:
repo = "https://hg.mozilla.org/mozilla-central" # Always use tip as the tag for nightly; this isn't quite right # but to do better we need the actual build revision, which we # can get if we have an application.ini file
tag = "tip"
def install_prefs(self, binary, dest=None, channel=None): if binary andnot binary.endswith(".apk"):
version, channel_ = self.get_version_and_channel(binary) if channel isnotNoneand channel != channel_: # Beta doesn't always seem to have the b in the version string, so allow the # manually supplied value to override the one from the binary
self.logger.warning("Supplied channel doesn't match binary, using supplied channel") elif channel isNone:
channel = channel_ else:
version = None
if dest isNone:
dest = os.curdir
dest = os.path.join(dest, "profiles", channel) if version:
dest = os.path.join(dest, version)
have_cache = False if os.path.exists(dest) and os.path.exists(os.path.join(dest, "profiles.json")): if channel != "nightly":
have_cache = True else:
now = datetime.now()
have_cache = (datetime.fromtimestamp(os.stat(dest).st_mtime) >
now - timedelta(days=1))
# If we don't have a recent download, grab and extract the latest one ifnot have_cache: if os.path.exists(dest):
rmtree(dest)
os.makedirs(dest)
self.logger.info(f"Downloading test prefs from {url}") try:
extract_dir = tempfile.mkdtemp()
unzip(get(url).raw, dest=extract_dir)
profiles = os.path.join(extract_dir, os.listdir(extract_dir)[0], 'testing', 'profiles') for name in os.listdir(profiles):
path = os.path.join(profiles, name)
shutil.move(path, dest) finally:
rmtree(extract_dir)
self.logger.info(f"Test prefs downloaded to {dest}") else:
self.logger.info(f"Using cached test prefs from {dest}")
return dest
def _latest_geckodriver_version(self): """Get and return latest version number for geckodriver.""" # This is used rather than an API call to avoid rate limits
tags = call("git", "ls-remote", "--tags", "--refs", "https://github.com/mozilla/geckodriver.git")
release_re = re.compile(r".*refs/tags/v(\d+)\.(\d+)\.(\d+)")
latest_release = (0, 0, 0) for item in tags.split("\n"):
m = release_re.match(item) if m:
version = tuple(int(item) for item in m.groups()) if version > latest_release:
latest_release = version assert latest_release != (0, 0, 0) return"v%s.%s.%s" % tuple(str(item) for item in latest_release)
def install_webdriver(self, dest=None, channel=None, browser_binary=None): """Install latest Geckodriver.""" if dest isNone:
dest = os.getcwd()
path = None if channel == "nightly":
path = self.install_geckodriver_nightly(dest) if path isNone:
self.logger.warning("Nightly webdriver not found; falling back to release")
if path isNone:
version = self._latest_geckodriver_version()
format = "zip"if uname[0] == "Windows"else"tar.gz"
self.logger.debug("Latest geckodriver release %s" % version)
url = ("https://github.com/mozilla/geckodriver/releases/download/%s/geckodriver-%s-%s.%s" %
(version, version, self.platform_string_geckodriver(), format)) if format == "zip":
unzip(get(url).raw, dest=dest) else:
untar(get(url).raw, dest=dest)
path = which("geckodriver", path=dest)
def _get_latest_chromium_revision(self): """Returns latest Chromium revision available for download.""" # This is only used if the user explicitly passes "latest" for the revision flag. # The pinned revision is used by default to avoid unexpected failures as versions update.
revision_url = ("https://storage.googleapis.com/chromium-browser-snapshots/"
f"{self._chromium_platform_string}/LAST_CHANGE") return get(revision_url).text.strip()
def _get_chromium_revision(self, filename=None, version=None): """Retrieve a valid Chromium revision to download a browser component."""
# If a specific version is passed as an argument, we will use it. if version isnotNone: # Detect a revision number based on the version passed.
revision = self._get_base_revision_from_version(version) if revision isnotNone: # File name is needed to test if request is valid.
url = self._build_snapshots_url(revision, filename) try: # Check the status without downloading the content (this is a streaming request).
get(url) return revision except requests.RequestException:
self.logger.warning("404: Unsuccessful attempt to download file "
f"based on version. {url}") # If no URL was used in a previous install # and no version was passed, use the pinned Chromium revision.
revision = self._get_pinned_chromium_revision()
# If the url is successfully used to download/install, it will be used again # if another component is also installed during this run (browser/webdriver). return revision
def _get_base_revision_from_version(self, version): """Get a Chromium revision number that is associated with a given version.""" # This is not the single revision associated with the version, # but instead is where it branched from. Chromium revisions are just counting # commits on the master branch, there are no Chromium revisions for branches.
version = self._remove_version_suffix(version)
# Try to find the Chromium build with the same revision. try:
omaha = get(f"https://omahaproxy.appspot.com/deps.json?version={version}").json()
detected_revision = omaha['chromium_base_position'] return detected_revision except requests.RequestException:
self.logger.debug("Unsuccessful attempt to detect revision based on version") returnNone
def _remove_existing_chromedriver_binary(self, path): """Remove an existing ChromeDriver for this product if it exists in the virtual environment. """ # There may be an existing chromedriver binary from a previous install. # To provide a clean install experience, remove the old binary - this # avoids tricky issues like unzipping over a read-only file.
existing_chromedriver_path = which("chromedriver", path=path) if existing_chromedriver_path:
self.logger.info(f"Removing existing ChromeDriver binary: {existing_chromedriver_path}")
os.chmod(existing_chromedriver_path, stat.S_IWUSR)
os.remove(existing_chromedriver_path)
def _remove_version_suffix(self, version): """Removes channel suffixes from Chrome/Chromium version string (e.g. " dev").""" return version.split(' ')[0]
@property def _chromedriver_platform_string(self): """Returns a string that represents the suffix of the ChromeDriver
file name when downloaded from Chromium Snapshots. """ if self.platform == "Linux":
bits = "64"if uname[4] == "x86_64"else"32" elif self.platform == "Mac":
bits = "64" elif self.platform == "Win":
bits = "32" return f"{self.platform.lower()}{bits}"
@property def _chromium_platform_string(self): """Returns a string that is used for the platform directory in Chromium Snapshots""" if (self.platform == "Linux"or self.platform == "Win") and uname[4] == "x86_64": return f"{self.platform}_x64" if self.platform == "Mac"and uname.machine == "arm64": return"Mac_Arm" return self.platform
def install_mojojs(self, dest, browser_binary): """Install MojoJS web framework.""" # MojoJS is platform agnostic, but the version number must be an # exact match of the Chrome/Chromium version to be compatible.
chrome_version = self.version(binary=browser_binary) ifnot chrome_version: returnNone
chrome_version = self._remove_version_suffix(chrome_version)
try: # MojoJS version url must match the browser binary version exactly.
url = ("https://storage.googleapis.com/chrome-for-testing-public/"
f"{chrome_version}/mojojs.zip") # Check the status without downloading the content (this is a streaming request).
get(url) except requests.RequestException: # If a valid matching version cannot be found in the CfT archive, # download from Chromium snapshots bucket. However, # MojoJS is only bundled with Linux from Chromium snapshots. if self.platform == "Linux":
filename = "mojojs.zip"
revision = self._get_chromium_revision(filename, chrome_version)
url = self._build_snapshots_url(revision, filename) else:
self.logger.error("A valid MojoJS version cannot be found "
f"for browser binary version {chrome_version}.") returnNone
extracted = os.path.join(dest, "mojojs", "gen")
last_url_file = os.path.join(extracted, "DOWNLOADED_FROM") if os.path.exists(last_url_file): with open(last_url_file, "rt") as f:
last_url = f.read().strip() if last_url == url:
self.logger.info("Mojo bindings already up to date") return extracted
rmtree(extracted)
try:
self.logger.info(f"Downloading Mojo bindings from {url}")
unzip(get(url).raw, dest) with open(last_url_file, "wt") as f:
f.write(url) return extracted except Exception as e:
self.logger.error(f"Cannot enable MojoJS: {e}") returnNone
def install_webdriver_by_version(self, version, dest, revision=None):
dest = os.path.join(dest, self.product)
self._remove_existing_chromedriver_binary(dest) # _get_webdriver_url is implemented differently for Chrome and Chromium because # they download their respective versions of ChromeDriver from different sources.
url = self._get_webdriver_url(version, revision)
self.logger.info(f"Downloading ChromeDriver from {url}")
unzip(get(url).raw, dest)
# The two sources of ChromeDriver have different zip structures: # * Chromium archives the binary inside a chromedriver_* directory; # * Chrome archives the binary directly. # We want to make sure the binary always ends up directly in bin/.
chromedriver_dir = os.path.join(dest,
f"chromedriver_{self._chromedriver_platform_string}")
chromedriver_path = which("chromedriver", path=chromedriver_dir) if chromedriver_path isnotNone:
shutil.move(chromedriver_path, dest)
rmtree(chromedriver_dir)
def _get_existing_browser_revision(self, venv_path, channel):
revision = None try: # A file referencing the revision number is saved with the binary. # Check if this revision number exists and use it if it does.
path = os.path.join(self._get_browser_binary_dir(None, channel), "revision") with open(path) as f:
revision = f.read().strip() except FileNotFoundError: # If there is no information about the revision downloaded, # use the pinned revision.
revision = self._get_pinned_chromium_revision() return revision
def _find_binary_in_directory(self, directory): """Search for Chromium browser binary in a given directory.""" if uname[0] == "Darwin": return which("Chromium", path=os.path.join(directory,
self._chromium_package_name, "Chromium.app", "Contents", "MacOS")) # which will add .exe on Windows automatically. return which("chrome", path=os.path.join(directory, self._chromium_package_name))
# Make sure we use the same revision in an invocation. # If we have a url that was last used successfully during this run, # that url takes priority over trying to form another. if hasattr(self, "last_revision_used") and self.last_revision_used isnotNone: return self._build_snapshots_url(self.last_revision_used, filename) if revision isNone:
revision = self._get_chromium_revision(filename, version) elif revision == "latest":
revision = self._get_latest_chromium_revision() elif revision == "pinned":
revision = self._get_pinned_chromium_revision()
url = self._build_snapshots_url(revision, filename)
self.logger.info(f"Downloading Chromium from {url}")
resp = get(url)
installer_path = os.path.join(dest, filename) with open(installer_path, "wb") as f:
f.write(resp.content)
# Revision successfully used. Keep this revision if another component install is needed.
self.last_revision_used = revision with open(os.path.join(dest, "revision"), "w") as f:
f.write(revision) return installer_path
def install(self, dest=None, channel=None, version=None, revision=None):
dest = self._get_browser_binary_dir(dest, channel)
installer_path = self.download(dest, channel, version=version, revision=revision) with open(installer_path, "rb") as f:
unzip(f, dest)
os.remove(installer_path) return self._find_binary_in_directory(dest)
def install_webdriver(self, dest=None, channel=None, browser_binary=None, revision=None): if dest isNone:
dest = os.pwd
if revision isNone: # If a revision was not given, we will need to detect the browser version. # The ChromeDriver that is installed will match this version.
revision = self._get_existing_browser_revision(dest, channel)
def webdriver_supports_browser(self, webdriver_binary, browser_binary, browser_channel=None): """Check that the browser binary and ChromeDriver versions are a valid match."""
browser_version = self.version(browser_binary)
chromedriver_version = self.webdriver_version(webdriver_binary)
ifnot chromedriver_version:
self.logger.warning("Unable to get version for ChromeDriver "
f"{webdriver_binary}, rejecting it") returnFalse
ifnot browser_version: # If we can't get the browser version, # we just have to assume the ChromeDriver is good. returnTrue
# Because Chromium and its ChromeDriver should be pulled from the # same revision number, their version numbers should match exactly. if browser_version == chromedriver_version:
self.logger.debug("Browser and ChromeDriver versions match.") returnTrue
self.logger.warning(f"ChromeDriver version {chromedriver_version} does not match "
f"Chromium version {browser_version}.") returnFalse
class DownloadNotFoundError(Exception): """Raised when a download is not found for browser/webdriver installation.""" pass
class Chrome(ChromeChromiumBase): """Chrome-specific interface.
Includes browser binary installation and detection.
Webdriver installation and wptrunner setup shared in base classwith Chromium.
def _get_build_version(self, version): """Convert a Chrome/ChromeDriver version into MAJOR.MINOR.BUILD format."""
version_parts = version.split(".") if len(version_parts) < 3:
self.logger.info(f"Version {version} could not be formatted for build matching.") returnNone return".".join(version_parts[0:3])
def _get_webdriver_url(self, version, channel): """Get a ChromeDriver URL to download a version of ChromeDriver that matches
the browser binary version.
Raises: ValueError if the given version string could not be formatted.
Returns: A ChromeDriver download URL that matches the given Chrome version. """ # Remove version suffix if it exists. if version:
version = self._remove_version_suffix(version)
formatted_version = self._get_build_version(version) if formatted_version isNone: raise ValueError(f"Unknown version format: {version}")
major_version = version.split(".")[0]
# Chrome for Testing only has ChromeDriver downloads available for Chrome 115+. # If we are matching an older version of Chrome, use the old ChromeDriver source. if int(major_version) < 115: return self._get_old_webdriver_url(formatted_version)
# Check if a file exists containing the matching ChromeDriver version download URL. # This is generated when installing Chrome for Testing using the install command.
download_url_reference_file = os.path.join(
self._get_browser_binary_dir(None, channel), CHROMEDRIVER_SAVED_DOWNLOAD_FILE) if os.path.isfile(download_url_reference_file):
self.logger.info("Download info for matching ChromeDriver version found.") with open(download_url_reference_file, "r") as f: return f.read()
# If no ChromeDriver download URL reference file exists, # try to find a download URL based on the build version.
self.logger.info(f"Searching for ChromeDriver downloads for version {version}.")
download_url = self._get_webdriver_url_by_build(formatted_version) if download_url isNone:
milestone = version.split('.')[0]
self.logger.info(f'No ChromeDriver download found for build {formatted_version}. '
f'Finding latest available download for milestone {milestone}')
download_url = self._get_webdriver_url_by_milestone(milestone) return download_url
def _get_old_webdriver_url(self, version): """Find a ChromeDriver download URL for Chrome version <= 114
Raises: DownloadNotFoundError if no ChromeDriver download URL is found
to match the given Chrome binary.
Returns: A ChromeDriver download URL that matches the given Chrome version. """
latest_url = ("https://chromedriver.storage.googleapis.com/LATEST_RELEASE_"
f"{version}") try:
latest = get(latest_url).text.strip() except requests.RequestException as e: raise DownloadNotFoundError("No matching ChromeDriver download"
f" found for version {version}.", e)
def _get_webdriver_url_by_build(self, version): """Find a ChromeDriver download URL based on a MAJOR.MINOR.BUILD version.
Raises: RequestException if a bad responses is received from
Chrome for Testing sources.
Returns: Download URL string orNoneif no matching build is found. """ try: # Get a list of builds with download URLs from Chrome for Testing.
resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}" "latest-patch-versions-per-build-with-downloads.json") except requests.RequestException as e: raise requests.RequestException( "Chrome for Testing versions not found", e)
builds_json = resp.json()
builds_dict = builds_json["builds"] if version notin builds_dict:
self.logger.info(f"No builds found for version {version}.") returnNone
download_info = builds_dict[version]["downloads"] if"chromedriver"notin download_info:
self.logger.info(f"No ChromeDriver download found for build {version}") returnNone
downloads_for_platform = [d for d in download_info["chromedriver"] if d["platform"] == self._chrome_platform_string] if len(downloads_for_platform) == 0:
self.logger.info(f"No ChromeDriver download found for build {version}"
f"of platform {self.platform}") returnNone return downloads_for_platform[0]["url"]
def _get_webdriver_url_by_milestone(self, milestone): """Find a ChromeDriver download URL that is the latest available for a Chrome milestone.
Raises: RequestException if a bad responses is received from
Chrome for Testing sources.
Returns: Download URL string orNoneif no matching milestone is found. """
try: # Get a list of builds with download URLs from Chrome for Testing.
resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}" "latest-versions-per-milestone.json") except requests.RequestException as e: raise requests.RequestException( "Chrome for Testing versions not found", e)
milestones_json = resp.json()
milestones_dict = milestones_json["milestones"] if milestone notin milestones_dict:
self.logger.info(f"No latest version found for milestone {milestone}.") returnNone
version_available = self._get_build_version(
milestones_dict[milestone]["version"])
def _get_download_urls_by_version(self, version): """Find Chrome for Testing and ChromeDriver download URLs matching a specific version.
Raises: DownloadNotFoundError if no download is found for the given version or platform.
RequestException if a bad responses is received from
Chrome for Testing sources.
Returns: Both binary downloads for Chrome and ChromeDriver. """ try: # Get a list of versions with download URLs from Chrome for Testing.
resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}" "known-good-versions-with-downloads.json") except requests.RequestException as e: raise requests.RequestException( "Chrome for Testing versions not found", e)
versions_json = resp.json()
versions_list = versions_json["versions"] # Attempt to find a version match in the list of available downloads.
matching_versions = [v for v in versions_list if v["version"] == version] if len(matching_versions) == 0: raise DownloadNotFoundError(f"No Chrome for Testing download found for {version}")
download_info = matching_versions[0]["downloads"] # Find the download url that matches the current platform.
browser_download_urls = [d for d in download_info["chrome"] if d["platform"] == self._chrome_platform_string] if len(browser_download_urls) == 0: raise DownloadNotFoundError(
f"No Chrome for Testing download found for {self.platform} of version {version}")
browser_download_url = browser_download_urls[0]["url"]
# Get the corresponding ChromeDriver download URL for later use.
chromedriver_download_urls = [d for d in download_info["chromedriver"] if d["platform"] == self._chrome_platform_string] if len(chromedriver_download_urls) == 0: # Some older versions of Chrome for Testing # do not have a matching ChromeDriver download. raise DownloadNotFoundError(
f"ChromeDriver download does not exist for version {version}")
chromedriver_url = chromedriver_download_urls[0]["url"]
return browser_download_url, chromedriver_url
def _get_download_urls_by_channel(self, channel): """Find Chrome for Testing and ChromeDriver download URLs matching the given channel.
Raises: DownloadNotFoundError if no download is found for the given channel or platform.
RequestException if a bad responses is received from Chrome for Testing sources.
Returns: Both binary downloads for Chrome and ChromeDriver. """ try:
resp = get(f"{CHROME_FOR_TESTING_ROOT_URL}" "last-known-good-versions-with-downloads.json") except requests.RequestException as e: raise requests.RequestException( "Chrome for Testing versions not found", e)
channels_json = resp.json()
download_info = channels_json["channels"][channel.capitalize()]["downloads"]["chrome"]
# Find the download URL that matches the current platform.
matching_download_urls = [d for d in download_info if d["platform"] == self._chrome_platform_string] if len(matching_download_urls) == 0: raise DownloadNotFoundError("No matching download for platform "
f"{self.platform} of channel \"{channel}\".")
# Get the corresponding ChromeDriver download URL for later use.
chromedriver_download_info = (
channels_json["channels"][channel.capitalize()]["downloads"]["chromedriver"])
matching_chromedriver_urls = [d for d in chromedriver_download_info if d["platform"] == self._chrome_platform_string] if len(matching_chromedriver_urls) == 0: raise DownloadNotFoundError(
f"No ChromeDriver download found in Chrome for Testing {channel}.")
chromedriver_url = matching_chromedriver_urls[0]["url"]
return browser_download_url, chromedriver_url
def _save_chromedriver_download_info(self, dest, url): """Save the download URL of a ChromeDriver binary that matches the browser.
This will allow for easy version matching, even in separate CLI invocations. """ with open(os.path.join(dest, CHROMEDRIVER_SAVED_DOWNLOAD_FILE), "w") as f:
f.write(url)
def download(self, dest=None, channel="canary", rename=None, version=None): """Download Chrome for Testing. For more information,
see: https://github.com/GoogleChromeLabs/chrome-for-testing """
dest = self._get_browser_binary_dir(None, channel)
filename = f"{self._chrome_package_name}.zip"
# If a version has been supplied, try to find a download to match that version. # Otherwise, find a download for the specified channel. if version isnotNone:
download_url, chromedriver_url = self._get_download_urls_by_version(version) else:
download_url, chromedriver_url = self._get_download_urls_by_channel(channel)
self.logger.info(f"Downloading Chrome for Testing from {download_url}")
resp = get(download_url)
installer_path = os.path.join(dest, filename) with open(installer_path, "wb") as f:
f.write(resp.content)
# Save the ChromeDriver download URL for use if a matching ChromeDriver # needs to be downloaded in a separate install invocation.
self._save_chromedriver_download_info(dest, chromedriver_url)
return installer_path
def _find_binary_in_directory(self, directory): """Search for Chrome for Testing browser binary in a given directory.""" if uname[0] == "Darwin": return which( "Google Chrome for Testing",
path=os.path.join(directory,
self._chrome_package_name, "Google Chrome for Testing.app", "Contents", "MacOS")) # "which" will add .exe on Windows automatically. return which("chrome", path=os.path.join(directory, self._chrome_package_name))
def find_binary(self, venv_path=None, channel=None): # Check for binary in venv first.
path = self._find_binary_in_directory(self._get_browser_binary_dir(venv_path, channel)) if path isnotNone: return path
if uname[0] == "Linux":
name = "google-chrome" if channel == "stable":
name += "-stable" elif channel == "beta":
name += "-beta" elif channel == "dev":
name += "-unstable" # No Canary on Linux. return which(name) if uname[0] == "Darwin":
suffix = "" if channel in ("beta", "dev", "canary"):
suffix = " " + channel.capitalize() return f"/Applications/Google Chrome{suffix}.app/Contents/MacOS/Google Chrome{suffix}" if uname[0] == "Windows":
name = "Chrome" if channel == "beta":
name += " Beta" elif channel == "dev":
name += " Dev"
path = os.path.expandvars(fr"$PROGRAMFILES\Google\{name}\Application\chrome.exe") if channel == "canary":
path = os.path.expandvars(r"$LOCALAPPDATA\Google\Chrome SxS\Application\chrome.exe") return path
self.logger.warning("Unable to find the browser binary.") returnNone
def install(self, dest=None, channel=None, version=None):
dest = self._get_browser_binary_dir(dest, channel)
installer_path = self.download(dest=dest, channel=channel, version=version) with open(installer_path, "rb") as f:
unzip(f, dest)
os.remove(installer_path) return self._find_binary_in_directory(dest)
def install_webdriver(self, dest=None, channel=None, browser_binary=None): if dest isNone:
dest = os.pwd
# Detect the browser version. # The ChromeDriver that is installed will match this version. if browser_binary isNone: # If a browser binary path was not given, detect a valid path.
browser_binary = self.find_binary(channel=channel) # We need a browser to version match, so if a browser binary path # was not given and cannot be detected, raise an error. if browser_binary isNone: raise FileNotFoundError("No browser binary detected. " "Cannot install ChromeDriver without a browser version.")
version = self.version(browser_binary) if version isNone: # Check if the user has given a Chromium binary.
chromium = Chromium(self.logger) if chromium.version(browser_binary): raise ValueError("Provided binary is a Chromium binary and should be run using " "\"./wpt run chromium\" or similar.") raise ValueError(f"Unable to detect browser version from binary at {browser_binary}. " " Cannot install ChromeDriver without a valid version to match.")
def install_webdriver_by_version(self, version, dest, channel): # Set the destination to a specific "chrome" folder to not overwrite or remove # ChromeDriver versions used for Chromium.
dest = os.path.join(dest, self.product)
self._remove_existing_chromedriver_binary(dest)
url = self._get_webdriver_url(version, channel) if url isNone: raise DownloadNotFoundError(
f"No ChromeDriver download found to match browser version {version}")
self.logger.info(f"Downloading ChromeDriver from {url}")
unzip(get(url).raw, dest)
if chromedriver_path isnotNone:
shutil.move(chromedriver_path, dest)
rmtree(chromedriver_dir)
chromedriver_path = which("chromedriver", path=dest) if chromedriver_path isNone: raise FileNotFoundError("ChromeDriver could not be detected after installation.") return chromedriver_path
def webdriver_supports_browser(self, webdriver_binary, browser_binary, browser_channel): """Check that the browser binary and ChromeDriver versions are a valid match."""
browser_version = self.version(browser_binary)
chromedriver_version = self.webdriver_version(webdriver_binary)
ifnot chromedriver_version:
self.logger.warning("Unable to get version for ChromeDriver "
f"{webdriver_binary}, rejecting it") returnFalse
# TODO(DanielRyanSmith): Determine if this version logic fail case is # still necessary and remove it if it isn't. ifnot browser_version: # If we can't get the browser version, # we just have to assume the ChromeDriver is good. returnTrue
# Format versions for comparison.
browser_version = self._get_build_version(browser_version)
chromedriver_version = self._get_build_version(chromedriver_version)
# Chrome and ChromeDriver versions should match on the same MAJOR.MINOR.BUILD version. if browser_version isnotNoneand browser_version != chromedriver_version: # Consider the same milestone as matching. # Workaround for https://github.com/web-platform-tests/wpt/issues/42545 # TODO(DanielRyanSmith): Remove this logic when browser binary is # downloaded from Chrome for Testing in CI runs.
browser_milestone = browser_version.split('.')[0]
chromedriver_milestone = chromedriver_version.split('.')[0] if browser_milestone != chromedriver_milestone:
self.logger.warning(
f"ChromeDriver {chromedriver_version} does not match Chrome {browser_version}") returnFalse returnTrue
def version(self, binary=None, webdriver_binary=None): """Get version string from browser binary.""" ifnot binary:
self.logger.warning("No browser binary provided.") returnNone if uname[0] == "Windows": return _get_fileversion(binary, self.logger)
try:
version_string = call(binary, "--version").strip() except (subprocess.CalledProcessError, OSError) as e:
self.logger.warning(f"Failed to call {binary}: {e}") returnNone
m = re.match(r"(?:Google Chrome for Testing|Google Chrome) (.*)", version_string) ifnot m:
self.logger.warning(f"Failed to extract version from: {version_string}") returnNone return m.group(1)
def webdriver_version(self, webdriver_binary): """Get version string from ChromeDriver binary.""" if webdriver_binary isNone:
self.logger.warning("No valid webdriver supplied to detect version.") returnNone
try:
version_string = call(webdriver_binary, "--version").strip() except (subprocess.CalledProcessError, OSError) as e:
self.logger.warning(f"Failed to call {webdriver_binary}: {e}") returnNone
m = re.match(r"ChromeDriver ([0-9][0-9.]*)", version_string) ifnot m:
self.logger.warning(f"Failed to extract version from: {version_string}") returnNone return m.group(1)
class HeadlessShell(ChromeChromiumBase): """Interface for the Chromium headless shell [0].
def find_binary(self, venv_path=None, channel=None): # `which()` adds `.exe` extension automatically for Windows. # Chromium builds an executable named `headless_shell`, whereas CfT # ships under the name `chrome-headless-shell`. return which("headless_shell") or which("chrome-headless-shell")
def version(self, binary=None, webdriver_binary=None): # TODO(crbug.com/327767951): Support `headless_shell --version`. return"N/A"
class ChromeAndroidBase(Browser): """A base class for ChromeAndroid and AndroidWebView.
On Android, WebView is based on Chromium open source project, and on some
versions of Android we share the library with Chrome. Therefore, we have
a very similar WPT runner implementation.
Includes webdriver installation. """
__metaclass__ = ABCMeta # This is an abstract class.
command = [self.adb_binary] if self.device_serial: # Assume we have same version of browser on all devices
command.extend(['-s', self.device_serial[0]])
command.extend(['shell', 'dumpsys', 'package', binary]) try:
output = call(*command) except (subprocess.CalledProcessError, OSError):
self.logger.warning("Failed to call %s" % " ".join(command)) returnNone
match = re.search(r'versionName=(.*)', output) ifnot match:
self.logger.warning("Failed to find versionName") returnNone return match.group(1)
class ChromeAndroid(ChromeAndroidBase): """Chrome-specific interface for Android. """
def find_binary(self, venv_path=None, channel=None): # Just get the current package name of the WebView provider. # For WebView, it is not trivial to change the WebView provider, so # we will just grab whatever is available. # https://chromium.googlesource.com/chromium/src/+/HEAD/android_webview/docs/channels.md
command = [self.adb_binary] if self.device_serial:
command.extend(['-s', self.device_serial[0]])
command.extend(['shell', 'dumpsys', 'webviewupdate']) try:
output = call(*command) except (subprocess.CalledProcessError, OSError):
self.logger.warning("Failed to call %s" % " ".join(command)) returnNone
m = re.search(r'^\s*Current WebView package \(name, version\): \((.*), ([0-9.]*)\)$',
output, re.M) if m isNone:
self.logger.warning("Unable to find current WebView package in dumpsys output") returnNone
self.logger.warning("Final package name: " + m.group(1)) return m.group(1)
class ChromeiOS(Browser): """Chrome-specific interface for iOS. """
def version(self, binary=None, webdriver_binary=None): if webdriver_binary isNone:
self.logger.warning( "Cannot find ChromeiOS version without CWTChromeDriver") returnNone # Use `chrome iOS driver --version` to get the version. Example output: # "125.0.6378.0" try:
version_string = call(webdriver_binary, "--version").strip() except subprocess.CalledProcessError as e:
self.logger.warning(f"Failed to call {webdriver_binary}: {e}") returnNone
m = re.match(r"[\d][\d\.]*", version_string) ifnot m:
self.logger.warning(
f"Failed to extract version from: {version_string}") returnNone return m.group(0)
class Opera(Browser): """Opera-specific interface.
Includes webdriver installation, and wptrunner setup methods. """
Die Informationen auf dieser Webseite wurden
nach bestem Wissen sorgfältig zusammengestellt. Es wird jedoch weder Vollständigkeit, noch Richtigkeit,
noch Qualität der bereit gestellten Informationen zugesichert.
Bemerkung:
Die farbliche Syntaxdarstellung und die Messung sind noch experimentell.