# This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/.
Browsertime is a harness for running performance tests, similar to
Mozilla's Raptor testing framework. Browsertime is written in Node.js and uses Selenium WebDriver to drive multiple browsers including
Chrome, Chrome for Android, Firefox, and (pending the resolution of
[Bug 1525126](https://bugzilla.mozilla.org/show_bug.cgi?id=1525126) and similar tickets) Firefox for Android and GeckoView-based vehicles.
Right now a custom version of browsertime and the underlying
geckodriver binary are needed to support GeckoView-based vehicles;
this module accommodates those in-progress custom versions.
To get started, run
```
./mach browsertime --setup [--clobber]
```
This will populate `tools/browsertime/node_modules`.
To invoke browsertime, run
```
./mach browsertime [ARGS]
```
All arguments are passed through to browsertime. """
import argparse import collections import contextlib import json import logging import os import platform import re import stat import subprocess import sys import time
import mozpack.path as mozpath from mach.decorators import Command, CommandArgument from mozbuild.base import BinaryNotFoundException, MachCommandBase from mozbuild.dirutils import mkdir from six import StringIO
NODE_FAILURE_MSG = ( "Could not locate a node binary that is at least version {}. ".format(
MIN_NODE_VERSION
)
+ "Please run `./mach raptor --browsertime -t amazon` to install it "
+ "from the Taskcluster Toolchain artifacts."
)
# Check standard locations first
node_exe = find_node_executable(min_version=Version(MIN_NODE_VERSION)) if node_exe and (node_exe[0] isnotNone): return os.path.abspath(node_exe[0]) ifnot os.path.exists(cache_path): raise Exception(NODE_FAILURE_MSG)
def browsertime_path(): """The path to the `browsertime.js` script.""" # On Windows, invoking `node_modules/.bin/browsertime{.cmd}` # doesn't work when invoked as an argument to our specific # binary. Since we want our version of node, invoke the # actual script directly. return mozpath.join(package_path(), "bin", "browsertime.js")
def visualmetrics_path(): """The path to the `visualmetrics.py` script.""" return mozpath.join(package_path(), "visualmetrics", "visualmetrics-portable.py")
if sys.platform.startswith("win"): if is_64bits: return"win64" elif sys.platform.startswith("linux"): if is_64bits: return"linux64" elif sys.platform.startswith("darwin"): return"darwin"
raise ValueError("sys.platform is not yet supported: {}".format(sys.platform))
def artifact_cache_path(command_context):
r"""Downloaded artifacts will be kept here.""" # The convention is $MOZBUILD_STATE_PATH/cache/$FEATURE. return mozpath.join(command_context._mach_context.state_dir, "cache", "browsertime")
def state_path(command_context):
r"""Unpacked artifacts will be kept here.""" # The convention is $MOZBUILD_STATE_PATH/$FEATURE. return mozpath.join(command_context._mach_context.state_dir, "browsertime")
def setup_prerequisites(command_context):
r"""Install browsertime and visualmetrics.py prerequisites."""
from mozbuild.action.tooltool import unpack_file from mozbuild.artifact_cache import ArtifactCache
# Make sure the expected path exists after extraction
path = os.path.join(state_path(command_context), fetch.get("path")) ifnot os.path.exists(path): raise Exception("Cannot find an extracted directory: %s" % path)
try: # Some archives provide binaries that don't have the # executable bit set so we need to set it here for root, dirs, files in os.walk(path): for edir in dirs:
loc_to_change = os.path.join(root, edir)
st = os.stat(loc_to_change)
os.chmod(loc_to_change, st.st_mode | stat.S_IEXEC) for efile in files:
loc_to_change = os.path.join(root, efile)
st = os.stat(loc_to_change)
os.chmod(loc_to_change, st.st_mode | stat.S_IEXEC) except Exception as e: raise Exception( "Could not set executable bit in %s, error: %s" % (path, str(e))
) finally:
os.chdir(cwd)
def setup_browsertime(
command_context,
should_clobber=False,
new_upstream_url="",
install_vismet_reqs=False,
):
r"""Install browsertime and visualmetrics.py prerequisites and the Node.js package."""
if new_upstream_url:
package_json_path = os.path.join(BROWSERTIME_ROOT, "package.json")
command_context.log(
logging.INFO, "browsertime",
{ "new_upstream_url": new_upstream_url, "package_json_path": package_json_path,
}, "Updating browsertime node module version in {package_json_path} " "to {new_upstream_url}",
)
ifnot re.search("/tarball/[a-f0-9]{40}$", new_upstream_url): raise ValueError( "New upstream URL does not end with /tarball/[a-f0-9]{40}: '%s'"
% new_upstream_url
)
with open(package_json_path) as f:
existing_body = json.loads(
f.read(), object_pairs_hook=collections.OrderedDict
)
with open(package_json_path, "w") as f:
f.write(updated_body)
# Install the browsertime Node.js requirements. ifnot setup_helper.check_node_executables_valid(): return 1
# To use a custom `geckodriver`, set # os.environ[b"GECKODRIVER_BASE_URL"] = bytes(url) # to an endpoint with binaries named like # https://github.com/sitespeedio/geckodriver/blob/master/install.js#L31. if AUTOMATION:
os.environ["CHROMEDRIVER_SKIP_DOWNLOAD"] = "true"
os.environ["GECKODRIVER_SKIP_DOWNLOAD"] = "true"
if install_vismet_reqs: # Hide this behind a flag so we don't install them by default in Raptor
command_context.log(
logging.INFO, "browsertime", {}, "Installing python requirements"
)
activate_browsertime_virtualenv(command_context)
# Add the mozbuild Node binary path to the OS environment in Apple Silicon. # During the browesertime installation, it seems installation of sitespeed.io # sub dependencies look for a global Node rather than the mozbuild Node binary. # Normally `--scripts-prepend-node-path` should prevent this but it seems to still # look for a system Node in the environment. This logic ensures the same Node is used.
node_dir = os.path.dirname(node_path(command_context)) if IS_APPLE_SILICON and node_dir notin os.environ["PATH"]:
os.environ["PATH"] += os.pathsep + node_dir
status = setup_helper.package_setup(
BROWSERTIME_ROOT, "browsertime",
should_update=new_upstream_url != "",
should_clobber=should_clobber,
no_optional=new_upstream_url or AUTOMATION,
)
if status: return status if new_upstream_url or AUTOMATION: return 0 if install_vismet_reqs: return check(command_context)
return 0
def node(command_context, args):
r"""Invoke node (interactively) with the given arguments.""" return command_context.run_process(
[node_path(command_context)] + args,
append_env=append_env(command_context),
pass_thru=True, # Allow user to run Node interactively.
ensure_exit_code=False, # Don't throw on non-zero exit code.
cwd=mozpath.join(command_context.topsrcdir),
)
# Ensure that `ffmpeg` is found and added to the environment
path = os.environ.get("PATH", "").split(os.pathsep) if append_path else []
path_to_ffmpeg = mozpath.join(
state_path(command_context), fetches["ffmpeg"]["path"]
)
# Ensure that bare `node` and `npm` in scripts, including post-install # scripts, finds the binary we're invoking with. Without this, it's # easy for compiled extensions to get mismatched versions of the Node.js # extension API.
node_dir = os.path.dirname(node_path(command_context))
path = [node_dir] + path
append_env = { "PATH": os.pathsep.join(path), # Bug 1560193: The JS library browsertime uses to execute commands # (execa) will muck up the PATH variable and put the directory that # node is in first in path. If this is globally-installed node, # that means `/usr/bin` will be inserted first which means that we # will get `/usr/bin/python` for `python`. # # Our fork of browsertime supports a `PYTHON` environment variable # that points to the exact python executable to use. "PYTHON": command_context.virtualenv_manager.python_path,
}
return append_env
def _need_install(command_context, package): from pip._internal.req.constructors import install_req_from_line
This function will also install Pillow and pyssim if needed.
It will raise an error in case the install failed. """ # TODO: Remove `./mach browsertime` completely, as a follow up to Bug 1758990
MachCommandBase.activate_virtualenv(command_context, *args, **kwargs)
# installing Python deps on the fly for dep in ( "Pillow==%s" % PILLOW_VERSION, "pyssim==%s" % PYSSIM_VERSION, "scipy==%s" % SCIPY_VERSION, "numpy==%s" % NUMPY_VERSION, "opencv-python==%s" % OPENCV_VERSION,
): if _need_install(command_context, dep):
subprocess.check_call(
[
command_context.virtualenv_manager.python_path, "-m", "pip", "install",
dep,
]
)
args = ["--check"]
status = command_context.run_process(
[command_context.virtualenv_manager.python_path, visualmetrics_path()] + args, # For --check, don't allow user's path to interfere with path testing except on Linux
append_env=append_env(
command_context, append_path=host_platform().startswith("linux")
),
pass_thru=True,
ensure_exit_code=False, # Don't throw on non-zero exit code.
cwd=mozpath.join(command_context.topsrcdir),
)
sys.stdout.flush()
sys.stderr.flush()
if status: return status
# Avoid logging the command (and, on Windows, the environment).
command_context.log_manager.terminal_handler.setLevel(logging.CRITICAL)
print("browsertime version:", end=" ")
def extra_default_args(command_context, args=[]): # Add Mozilla-specific default arguments. This is tricky because browsertime is quite # loose about arguments; repeat arguments are generally accepted but then produce # difficult to interpret type errors.
def extract_browser_name(args): "Extracts the browser name if any" # These are BT arguments, it's BT job to check them # here we just want to extract the browser name
res = re.findall(r"(--browser|-b)[= ]([\w]+)", " ".join(args)) if res == []: returnNone return res[0][-1]
def matches(args, *flags): "Return True if any argument matches any of the given flags (maybe with an argument)." for flag in flags: if flag in args or any(arg.startswith(flag + "=") for arg in args): returnTrue returnFalse
extra_args = []
# Default to Firefox. Override with `-b ...` or `--browser=...`.
specifies_browser = matches(args, "-b", "--browser") ifnot specifies_browser:
extra_args.extend(("-b", "firefox"))
# Default to not collect HAR. Override with `--skipHar=false`.
specifies_har = matches(args, "--har", "--skipHar", "--gzipHar") ifnot specifies_har:
extra_args.append("--skipHar")
ifnot matches(args, "--android"): # If --firefox.binaryPath is not specified, default to the objdir binary # Note: --firefox.release is not a real browsertime option, but it will # silently ignore it instead and default to a release installation.
specifies_binaryPath = matches(
args, "--firefox.binaryPath", "--firefox.release", "--firefox.nightly", "--firefox.beta", "--firefox.developer",
)
ifnot specifies_binaryPath: try:
extra_args.extend(
("--firefox.binaryPath", command_context.get_binary_path())
) except BinaryNotFoundException as e:
command_context.log(
logging.ERROR, "browsertime",
{"error": str(e)}, "ERROR: {error}",
)
command_context.log(
logging.INFO, "browsertime",
{}, "Please run |./mach build| " "or specify a Firefox binary with --firefox.binaryPath.",
) return 1
if extra_args:
command_context.log(
logging.DEBUG, "browsertime",
{"extra_args": extra_args}, "Running browsertime with extra default arguments: {extra_args}",
)
return extra_args
def _verify_node_install(command_context): # check if Node is installed
sys.path.append(mozpath.join(command_context.topsrcdir, "tools", "lint", "eslint")) import setup_helper
with silence():
node_valid = setup_helper.check_node_executables_valid() ifnot node_valid:
print("Can't find Node. did you run ./mach bootstrap ?") returnFalse
# check if the browsertime package has been deployed correctly # for this we just check for the browsertime directory presence ifnot os.path.exists(browsertime_path()):
print("Could not find browsertime.js, try ./mach browsertime --setup")
print("If that still fails, try ./mach browsertime --setup --clobber") returnFalse
returnTrue
@Command( "browsertime",
category="testing",
description="Run [browsertime](https://github.com/sitespeedio/browsertime) " "performance tests.",
)
@CommandArgument( "--verbose",
action="store_true",
help="Verbose output for what commands the build is running.",
)
@CommandArgument("--update-upstream-url", default="")
@CommandArgument("--setup", default=False, action="store_true")
@CommandArgument("--clobber", default=False, action="store_true")
@CommandArgument( "--skip-cache",
default=False,
action="store_true",
help="Skip all local caches to force re-fetching remote artifacts.",
)
@CommandArgument("--check-browsertime", default=False, action="store_true")
@CommandArgument( "--install-vismet-reqs",
default=False,
action="store_true",
help="Add this flag to get the visual metrics requirements installed.",
)
@CommandArgument( "--browsertime-help",
default=False,
action="store_true",
help="Show the browsertime help message.",
)
@CommandArgument("args", nargs=argparse.REMAINDER) def browsertime(
command_context,
args,
verbose=False,
update_upstream_url="",
setup=False,
clobber=False,
skip_cache=False,
check_browsertime=False,
browsertime_help=False,
install_vismet_reqs=False,
):
command_context._set_log_level(verbose)
# Output a message before going further to make sure the # user knows that this tool is unsupported by the perftest # team and point them to our supported tools. Pause a bit to # make sure the user sees this message.
command_context.log(
logging.INFO, "browsertime",
{}, "[INFO] This command should be used for browsertime setup only.\n" "If you are looking to run performance tests on your patch, use " "`./mach raptor --browsertime` instead.\n\nYou can get visual-metrics " "by using the --browsertime-video and --browsertime-visualmetrics. " "Here is a sample command for raptor-browsertime: \n\t`./mach raptor " "--browsertime -t amazon --browsertime-video --browsertime-visualmetrics`\n\n" "See this wiki page for more information if needed: " "https://wiki.mozilla.org/TestEngineering/Performance/Raptor/Browsertime\n\n",
)
time.sleep(5)
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 ist noch experimentell.