Source code
Revision control
Copy as Markdown
Other Tools
# 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
"""
Runs the Mochitest test harness.
"""
import os
import sys
SCRIPT_DIR = os.path.abspath(os.path.realpath(os.path.dirname(__file__)))
sys.path.insert(0, SCRIPT_DIR)
import ctypes
import glob
import json
import numbers
import platform
import re
import shlex
import shutil
import signal
import socket
import subprocess
import sys
import tempfile
import time
import traceback
import uuid
import zipfile
from argparse import Namespace
from collections import defaultdict
from contextlib import closing
from ctypes.util import find_library
from datetime import datetime, timedelta
from shutil import which
import bisection
import mozcrash
import mozdebug
import mozinfo
import mozprocess
import mozrunner
from manifestparser import TestManifest
from manifestparser.filters import (
chunk_by_dir,
chunk_by_runtime,
chunk_by_slice,
failures,
pathprefix,
subsuite,
tags,
)
from manifestparser.util import normsep
from mozgeckoprofiler import (
symbolicate_profile_json,
view_gecko_profile,
)
from mozserve import DoHServer, Http2Server, Http3Server
try:
from marionette_driver.addons import Addons
from marionette_driver.marionette import Marionette
except ImportError as e: # noqa
error = e
# Defer ImportError until attempt to use Marionette
def reraise(*args, **kwargs):
raise error # noqa
Marionette = reraise
import mozleak
from leaks import LSANLeaks, ShutdownLeaks
from mochitest_options import (
MochitestArgumentParser,
build_obj,
get_default_valgrind_suppression_files,
)
from mozlog import commandline, get_proxy_logger
from mozprofile import Profile
from mozprofile.cli import KeyValueParseError, parse_key_value, parse_preferences
from mozprofile.permissions import ServerLocations
from mozrunner.utils import get_stack_fixer_function, test_environment
from mozscreenshot import dump_screen
HAVE_PSUTIL = False
try:
import psutil
HAVE_PSUTIL = True
except ImportError:
pass
import six
from six.moves.urllib.parse import quote_plus as encodeURIComponent
from six.moves.urllib_request import urlopen
try:
from mozbuild.base import MozbuildObject
build = MozbuildObject.from_environment(cwd=SCRIPT_DIR)
except ImportError:
build = None
here = os.path.abspath(os.path.dirname(__file__))
NO_TESTS_FOUND = """
No tests were found for flavor '{}' and the following manifest filters:
{}
Make sure the test paths (if any) are spelt correctly and the corresponding
--flavor and --subsuite are being used. See `mach mochitest --help` for a
list of valid flavors.
""".lstrip()
########################################
# Option for MOZ (former NSPR) logging #
########################################
# Set the desired log modules you want a log be produced
# by a try run for, or leave blank to disable the feature.
# This will be passed to MOZ_LOG environment variable.
# Try run will then put a download link for a zip archive
# of all the log files on treeherder.
MOZ_LOG = ""
########################################
# Option for web server log #
########################################
# If True, debug logging from the web server will be
# written to mochitest-server-%d.txt artifacts on
# treeherder.
MOCHITEST_SERVER_LOGGING = False
#####################
# Test log handling #
#####################
# output processing
TBPL_RETRY = 4 # Defined in mozharness
class MessageLogger(object):
"""File-like object for logging messages (structured logs)"""
BUFFERING_THRESHOLD = 100
# This is a delimiter used by the JS side to avoid logs interleaving
DELIMITER = "\ue175\uee31\u2c32\uacbf"
BUFFERED_ACTIONS = set(["test_status", "log"])
VALID_ACTIONS = set(
[
"suite_start",
"suite_end",
"group_start",
"group_end",
"test_start",
"test_end",
"test_status",
"log",
"assertion_count",
"buffering_on",
"buffering_off",
]
)
# Regexes that will be replaced with an empty string if found in a test
# name. We do this to normalize test names which may contain URLs and test
# package prefixes.
TEST_PATH_PREFIXES = [
r"^/tests/",
]
def __init__(self, logger, buffering=True, structured=True):
self.logger = logger
self.structured = structured
self.gecko_id = "GECKO"
self.is_test_running = False
self._manifest = None
# Even if buffering is enabled, we only want to buffer messages between
# TEST-START/TEST-END. So it is off to begin, but will be enabled after
# a TEST-START comes in.
self._buffering = False
self.restore_buffering = buffering
# Guard to ensure we never buffer if this value was initially `False`
self._buffering_initially_enabled = buffering
# Message buffering
self.buffered_messages = []
def setManifest(self, name):
self._manifest = name
def validate(self, obj):
"""Tests whether the given object is a valid structured message
(only does a superficial validation)"""
if not (
isinstance(obj, dict)
and "action" in obj
and obj["action"] in MessageLogger.VALID_ACTIONS
):
raise ValueError
def _fix_subtest_name(self, message):
"""Make sure subtest name is a string"""
if "subtest" in message and not isinstance(
message["subtest"], six.string_types
):
message["subtest"] = str(message["subtest"])
def _fix_test_name(self, message):
"""Normalize a logged test path to match the relative path from the sourcedir."""
if message.get("test") is not None:
test = message["test"]
for pattern in MessageLogger.TEST_PATH_PREFIXES:
test = re.sub(pattern, "", test)
if test != message["test"]:
message["test"] = test
break
def _fix_message_format(self, message):
if "message" in message:
if isinstance(message["message"], bytes):
message["message"] = message["message"].decode("utf-8", "replace")
elif not isinstance(message["message"], six.text_type):
message["message"] = six.text_type(message["message"])
def parse_line(self, line):
"""Takes a given line of input (structured or not) and
returns a list of structured messages"""
if isinstance(line, six.binary_type):
# if line is a sequence of bytes, let's decode it
line = line.rstrip().decode("UTF-8", "replace")
else:
# line is in unicode - so let's use it as it is
line = line.rstrip()
messages = []
for fragment in line.split(MessageLogger.DELIMITER):
if not fragment:
continue
try:
message = json.loads(fragment)
self.validate(message)
except ValueError:
if self.structured:
message = dict(
action="process_output",
process=self.gecko_id,
data=fragment,
)
else:
message = dict(
action="log",
level="info",
message=fragment,
)
self._fix_subtest_name(message)
self._fix_test_name(message)
self._fix_message_format(message)
message["group"] = self._manifest
messages.append(message)
return messages
@property
def buffering(self):
if not self._buffering_initially_enabled:
return False
return self._buffering
@buffering.setter
def buffering(self, val):
self._buffering = val
def process_message(self, message):
"""Processes a structured message. Takes into account buffering, errors, ..."""
# Activation/deactivating message buffering from the JS side
if message["action"] == "buffering_on":
if self.is_test_running:
self.buffering = True
return
if message["action"] == "buffering_off":
self.buffering = False
return
# Error detection also supports "raw" errors (in log messages) because some tests
# manually dump 'TEST-UNEXPECTED-FAIL'.
if "expected" in message or (
message["action"] == "log"
and message.get("message", "").startswith("TEST-UNEXPECTED")
):
self.restore_buffering = self.restore_buffering or self.buffering
self.buffering = False
if self.buffered_messages:
snipped = len(self.buffered_messages) - self.BUFFERING_THRESHOLD
if snipped > 0:
self.logger.info(
"<snipped {0} output lines - "
"if you need more context, please use "
"SimpleTest.requestCompleteLog() in your test>".format(snipped)
)
# Dumping previously buffered messages
self.dump_buffered(limit=True)
# Logging the error message
self.logger.log_raw(message)
# Determine if message should be buffered
elif (
self.buffering
and self.structured
and message["action"] in self.BUFFERED_ACTIONS
):
self.buffered_messages.append(message)
# Otherwise log the message directly
else:
self.logger.log_raw(message)
# If a test ended, we clean the buffer
if message["action"] == "test_end":
self.is_test_running = False
self.buffered_messages = []
self.restore_buffering = self.restore_buffering or self.buffering
self.buffering = False
if message["action"] == "test_start":
self.is_test_running = True
if self.restore_buffering:
self.restore_buffering = False
self.buffering = True
def write(self, line):
messages = self.parse_line(line)
for message in messages:
self.process_message(message)
return messages
def flush(self):
sys.stdout.flush()
def dump_buffered(self, limit=False):
if limit:
dumped_messages = self.buffered_messages[-self.BUFFERING_THRESHOLD :]
else:
dumped_messages = self.buffered_messages
last_timestamp = None
for buf in dumped_messages:
# pylint --py3k W1619
timestamp = datetime.fromtimestamp(buf["time"] / 1000).strftime("%H:%M:%S")
if timestamp != last_timestamp:
self.logger.info("Buffered messages logged at {}".format(timestamp))
last_timestamp = timestamp
self.logger.log_raw(buf)
self.logger.info("Buffered messages finished")
# Cleaning the list of buffered messages
self.buffered_messages = []
def finish(self):
self.dump_buffered()
self.buffering = False
self.logger.suite_end()
####################
# PROCESS HANDLING #
####################
def call(*args, **kwargs):
"""wraps mozprocess.run_and_wait with process output logging"""
log = get_proxy_logger("mochitest")
def on_output(proc, line):
cmdline = subprocess.list2cmdline(proc.args)
log.process_output(
process=proc.pid,
data=line,
command=cmdline,
)
process = mozprocess.run_and_wait(*args, output_line_handler=on_output, **kwargs)
return process.returncode
def killPid(pid, log):
if HAVE_PSUTIL:
# Kill a process tree (including grandchildren) with signal.SIGTERM
if pid == os.getpid():
raise RuntimeError("Error: trying to kill ourselves, not another process")
try:
parent = psutil.Process(pid)
children = parent.children(recursive=True)
children.append(parent)
for p in children:
p.send_signal(signal.SIGTERM)
gone, alive = psutil.wait_procs(children, timeout=30)
for p in gone:
log.info("psutil found pid %s dead" % p.pid)
for p in alive:
log.info("failed to kill pid %d after 30s" % p.pid)
except Exception as e:
log.info("Error: Failed to kill process %d: %s" % (pid, str(e)))
else:
try:
os.kill(pid, getattr(signal, "SIGKILL", signal.SIGTERM))
except Exception as e:
log.info("Failed to kill process %d: %s" % (pid, str(e)))
if mozinfo.isWin:
import ctypes.wintypes
def isPidAlive(pid):
STILL_ACTIVE = 259
PROCESS_QUERY_LIMITED_INFORMATION = 0x1000
pHandle = ctypes.windll.kernel32.OpenProcess(
PROCESS_QUERY_LIMITED_INFORMATION, 0, pid
)
if not pHandle:
return False
try:
pExitCode = ctypes.wintypes.DWORD()
ctypes.windll.kernel32.GetExitCodeProcess(pHandle, ctypes.byref(pExitCode))
if pExitCode.value != STILL_ACTIVE:
return False
# We have a live process handle. But Windows aggressively
# re-uses pids, so let's attempt to verify that this is
# actually Firefox.
namesize = 1024
pName = ctypes.create_string_buffer(namesize)
namelen = ctypes.windll.psapi.GetProcessImageFileNameA(
pHandle, pName, namesize
)
if namelen == 0:
# Still an active process, so conservatively assume it's Firefox.
return True
return pName.value.endswith((b"firefox.exe", b"plugin-container.exe"))
finally:
ctypes.windll.kernel32.CloseHandle(pHandle)
else:
import errno
def isPidAlive(pid):
try:
# kill(pid, 0) checks for a valid PID without actually sending a signal
# The method throws OSError if the PID is invalid, which we catch
# below.
os.kill(pid, 0)
# Wait on it to see if it's a zombie. This can throw OSError.ECHILD if
# the process terminates before we get to this point.
wpid, wstatus = os.waitpid(pid, os.WNOHANG)
return wpid == 0
except OSError as err:
# Catch the errors we might expect from os.kill/os.waitpid,
# and re-raise any others
if err.errno in (errno.ESRCH, errno.ECHILD, errno.EPERM):
return False
raise
# TODO: ^ upstream isPidAlive to mozprocess
#######################
# HTTP SERVER SUPPORT #
#######################
class MochitestServer(object):
"Web server used to serve Mochitests, for closer fidelity to the real web."
instance_count = 0
def __init__(self, options, logger):
if isinstance(options, Namespace):
options = vars(options)
self._log = logger
self._keep_open = bool(options["keep_open"])
self._utilityPath = options["utilityPath"]
self._xrePath = options["xrePath"]
self._profileDir = options["profilePath"]
self.webServer = options["webServer"]
self.httpPort = options["httpPort"]
if options.get("remoteWebServer") == "10.0.2.2":
# probably running an Android emulator and 10.0.2.2 will
# not be visible from host
shutdownServer = "127.0.0.1"
else:
shutdownServer = self.webServer
"server": shutdownServer,
"port": self.httpPort,
}
"server": shutdownServer,
"port": self.httpPort,
}
self.testPrefix = "undefined"
if options.get("httpdPath"):
self._httpdPath = options["httpdPath"]
else:
self._httpdPath = SCRIPT_DIR
self._httpdPath = os.path.abspath(self._httpdPath)
MochitestServer.instance_count += 1
def start(self):
"Run the Mochitest server, returning the process ID of the server."
# get testing environment
env = test_environment(xrePath=self._xrePath, log=self._log)
env["XPCOM_DEBUG_BREAK"] = "warn"
if "LD_LIBRARY_PATH" not in env or env["LD_LIBRARY_PATH"] is None:
env["LD_LIBRARY_PATH"] = self._xrePath
else:
env["LD_LIBRARY_PATH"] = ":".join([self._xrePath, env["LD_LIBRARY_PATH"]])
# When running with an ASan build, our xpcshell server will also be ASan-enabled,
# thus consuming too much resources when running together with the browser on
# the test machines. Try to limit the amount of resources by disabling certain
# features.
env["ASAN_OPTIONS"] = "quarantine_size=1:redzone=32:malloc_context_size=5"
# Likewise, when running with a TSan build, our xpcshell server will
# also be TSan-enabled. Except that in this case, we don't really
# care about races in xpcshell. So disable TSan for the server.
env["TSAN_OPTIONS"] = "report_bugs=0"
# Don't use socket process for the xpcshell server.
env["MOZ_DISABLE_SOCKET_PROCESS"] = "1"
if mozinfo.isWin:
env["PATH"] = env["PATH"] + ";" + str(self._xrePath)
args = [
"-g",
self._xrePath,
"-e",
"const _PROFILE_PATH = '%(profile)s'; const _SERVER_PORT = '%(port)s'; "
"const _SERVER_ADDR = '%(server)s'; const _TEST_PREFIX = %(testPrefix)s; "
"const _DISPLAY_RESULTS = %(displayResults)s; "
"const _HTTPD_PATH = '%(httpdPath)s';"
% {
"httpdPath": self._httpdPath.replace("\\", "\\\\"),
"profile": self._profileDir.replace("\\", "\\\\"),
"port": self.httpPort,
"server": self.webServer,
"testPrefix": self.testPrefix,
"displayResults": str(self._keep_open).lower(),
},
"-f",
os.path.join(SCRIPT_DIR, "server.js"),
]
xpcshell = os.path.join(
self._utilityPath, "xpcshell" + mozinfo.info["bin_suffix"]
)
command = [xpcshell] + args
if MOCHITEST_SERVER_LOGGING and "MOZ_UPLOAD_DIR" in os.environ:
server_logfile_path = os.path.join(
os.environ["MOZ_UPLOAD_DIR"],
"mochitest-server-%d.txt" % MochitestServer.instance_count,
)
self.server_logfile = open(server_logfile_path, "w")
self._process = subprocess.Popen(
command,
cwd=SCRIPT_DIR,
env=env,
stdout=self.server_logfile,
stderr=subprocess.STDOUT,
)
else:
self.server_logfile = None
self._process = subprocess.Popen(
command,
cwd=SCRIPT_DIR,
env=env,
)
self._log.info("%s : launching %s" % (self.__class__.__name__, command))
pid = self._process.pid
self._log.info("runtests.py | Server pid: %d" % pid)
if MOCHITEST_SERVER_LOGGING and "MOZ_UPLOAD_DIR" in os.environ:
self._log.info("runtests.py enabling server debugging...")
i = 0
while i < 5:
try:
with closing(urlopen(self.debugURL)) as c:
self._log.info(six.ensure_text(c.read()))
break
except Exception as e:
self._log.info("exception when enabling debugging: %s" % str(e))
time.sleep(1)
i += 1
def ensureReady(self, timeout):
assert timeout >= 0
aliveFile = os.path.join(self._profileDir, "server_alive.txt")
i = 0
while i < timeout:
if os.path.exists(aliveFile):
break
time.sleep(0.05)
i += 0.05
else:
self._log.error(
"TEST-UNEXPECTED-FAIL | runtests.py | Timed out while waiting for server startup."
)
self.stop()
sys.exit(1)
def stop(self):
try:
with closing(urlopen(self.shutdownURL)) as c:
self._log.info(six.ensure_text(c.read()))
except Exception:
self._log.info("Failed to stop web server on %s" % self.shutdownURL)
traceback.print_exc()
finally:
if self.server_logfile is not None:
self.server_logfile.close()
if self._process is not None:
# Kill the server immediately to avoid logging intermittent
# shutdown crashes, sometimes observed on Windows 10.
self._process.kill()
self._log.info("Web server killed.")
class WebSocketServer(object):
"Class which encapsulates the mod_pywebsocket server"
def __init__(self, options, scriptdir, logger, debuggerInfo=None):
self.port = options.webSocketPort
self.debuggerInfo = debuggerInfo
self._log = logger
self._scriptdir = scriptdir
def start(self):
# Invoke pywebsocket through a wrapper which adds special SIGINT handling.
#
# If we're in an interactive debugger, the wrapper causes the server to
# ignore SIGINT so the server doesn't capture a ctrl+c meant for the
# debugger.
#
# If we're not in an interactive debugger, the wrapper causes the server to
# die silently upon receiving a SIGINT.
scriptPath = "pywebsocket_wrapper.py"
script = os.path.join(self._scriptdir, scriptPath)
cmd = [sys.executable, script]
if self.debuggerInfo and self.debuggerInfo.interactive:
cmd += ["--interactive"]
# We need to use 0.0.0.0 to listen on all interfaces because
# Android tests connect from a different hosts
cmd += [
"-H",
"0.0.0.0",
"-p",
str(self.port),
"-w",
self._scriptdir,
"-l",
os.path.join(self._scriptdir, "websock.log"),
"--log-level=debug",
"--allow-handlers-outside-root-dir",
]
env = dict(os.environ)
env["PYTHONPATH"] = os.pathsep.join(sys.path)
# Start the process. Ignore stderr so that exceptions from the server
# are not treated as failures when parsing the test log.
self._process = subprocess.Popen(
cmd, cwd=SCRIPT_DIR, env=env, stderr=subprocess.DEVNULL
)
pid = self._process.pid
self._log.info("runtests.py | Websocket server pid: %d" % pid)
def stop(self):
if self._process is not None:
self._process.kill()
class SSLTunnel:
def __init__(self, options, logger):
self.log = logger
self.process = None
self.utilityPath = options.utilityPath
self.xrePath = options.xrePath
self.certPath = options.certPath
self.sslPort = options.sslPort
self.httpPort = options.httpPort
self.webServer = options.webServer
self.webSocketPort = options.webSocketPort
self.customCertRE = re.compile("^cert=(?P<nickname>[0-9a-zA-Z_ ]+)")
self.clientAuthRE = re.compile("^clientauth=(?P<clientauth>[a-z]+)")
self.redirRE = re.compile("^redir=(?P<redirhost>[0-9a-zA-Z_ .]+)")
def writeLocation(self, config, loc):
for option in loc.options:
match = self.customCertRE.match(option)
if match:
customcert = match.group("nickname")
config.write(
"listen:%s:%s:%s:%s\n"
% (loc.host, loc.port, self.sslPort, customcert)
)
match = self.clientAuthRE.match(option)
if match:
clientauth = match.group("clientauth")
config.write(
"clientauth:%s:%s:%s:%s\n"
% (loc.host, loc.port, self.sslPort, clientauth)
)
match = self.redirRE.match(option)
if match:
redirhost = match.group("redirhost")
config.write(
"redirhost:%s:%s:%s:%s\n"
% (loc.host, loc.port, self.sslPort, redirhost)
)
if option in (
"tls1",
"tls1_1",
"tls1_2",
"tls1_3",
"ssl3",
"3des",
"failHandshake",
):
config.write(
"%s:%s:%s:%s\n" % (option, loc.host, loc.port, self.sslPort)
)
def buildConfig(self, locations, public=None):
"""Create the ssltunnel configuration file"""
configFd, self.configFile = tempfile.mkstemp(prefix="ssltunnel", suffix=".cfg")
with os.fdopen(configFd, "w") as config:
config.write("httpproxy:1\n")
config.write("certdbdir:%s\n" % self.certPath)
config.write("forward:127.0.0.1:%s\n" % self.httpPort)
wsserver = self.webServer
if self.webServer == "10.0.2.2":
wsserver = "127.0.0.1"
config.write("websocketserver:%s:%s\n" % (wsserver, self.webSocketPort))
# Use "*" to tell ssltunnel to listen on the public ip
# address instead of the loopback address 127.0.0.1. This
# may have the side-effect of causing firewall warnings on
# macOS and Windows. Use "127.0.0.1" to listen on the
# loopback address. Remote tests using physical or
# emulated Android devices must use the public ip address
# in order for the sslproxy to work but Desktop tests
# which run on the same host as ssltunnel may use the
# loopback address.
listen_address = "*" if public else "127.0.0.1"
config.write("listen:%s:%s:pgoserver\n" % (listen_address, self.sslPort))
for loc in locations:
if loc.scheme == "https" and "nocert" not in loc.options:
self.writeLocation(config, loc)
def start(self):
"""Starts the SSL Tunnel"""
# start ssltunnel to provide https:// URLs capability
ssltunnel = os.path.join(self.utilityPath, "ssltunnel")
if os.name == "nt":
ssltunnel += ".exe"
if not os.path.exists(ssltunnel):
self.log.error(
"INFO | runtests.py | expected to find ssltunnel at %s" % ssltunnel
)
sys.exit(1)
env = test_environment(xrePath=self.xrePath, log=self.log)
env["LD_LIBRARY_PATH"] = self.xrePath
self.process = subprocess.Popen([ssltunnel, self.configFile], env=env)
self.log.info("runtests.py | SSL tunnel pid: %d" % self.process.pid)
def stop(self):
"""Stops the SSL Tunnel and cleans up"""
if self.process is not None:
self.process.kill()
if os.path.exists(self.configFile):
os.remove(self.configFile)
def checkAndConfigureV4l2loopback(device):
"""
Determine if a given device path is a v4l2loopback device, and if so
toggle a few settings on it via fcntl. Very linux-specific.
Returns (status, device name) where status is a boolean.
"""
if not mozinfo.isLinux:
return False, ""
libc = ctypes.cdll.LoadLibrary(find_library("c"))
O_RDWR = 2
# These are from linux/videodev2.h
class v4l2_capability(ctypes.Structure):
_fields_ = [
("driver", ctypes.c_char * 16),
("card", ctypes.c_char * 32),
("bus_info", ctypes.c_char * 32),
("version", ctypes.c_uint32),
("capabilities", ctypes.c_uint32),
("device_caps", ctypes.c_uint32),
("reserved", ctypes.c_uint32 * 3),
]
VIDIOC_QUERYCAP = 0x80685600
fd = libc.open(six.ensure_binary(device), O_RDWR)
if fd < 0:
return False, ""
vcap = v4l2_capability()
if libc.ioctl(fd, VIDIOC_QUERYCAP, ctypes.byref(vcap)) != 0:
return False, ""
if six.ensure_text(vcap.driver) != "v4l2 loopback":
return False, ""
class v4l2_control(ctypes.Structure):
_fields_ = [("id", ctypes.c_uint32), ("value", ctypes.c_int32)]
# These are private v4l2 control IDs, see:
KEEP_FORMAT = 0x8000000
SUSTAIN_FRAMERATE = 0x8000001
VIDIOC_S_CTRL = 0xC008561C
control = v4l2_control()
control.id = KEEP_FORMAT
control.value = 1
libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control))
control.id = SUSTAIN_FRAMERATE
control.value = 1
libc.ioctl(fd, VIDIOC_S_CTRL, ctypes.byref(control))
libc.close(fd)
return True, six.ensure_text(vcap.card)
def findTestMediaDevices(log):
"""
Find the test media devices configured on this system, and return a dict
containing information about them. The dict will have keys for 'audio'
and 'video', each containing the name of the media device to use.
If audio and video devices could not be found, return None.
This method is only currently implemented for Linux.
"""
if not mozinfo.isLinux:
return None
info = {}
# Look for a v4l2loopback device.
name = None
device = None
for dev in sorted(glob.glob("/dev/video*")):
result, name_ = checkAndConfigureV4l2loopback(dev)
if result:
name = name_
device = dev
break
if not (name and device):
log.error("Couldn't find a v4l2loopback video device")
return None
# Feed it a frame of output so it has something to display
gst01 = which("gst-launch-0.1")
gst010 = which("gst-launch-0.10")
gst10 = which("gst-launch-1.0")
if gst01:
gst = gst01
if gst010:
gst = gst010
else:
gst = gst10
process = subprocess.Popen(
[
gst,
"--no-fault",
"videotestsrc",
"pattern=green",
"num-buffers=1",
"!",
"v4l2sink",
"device=%s" % device,
]
)
info["video"] = {"name": name, "process": process}
info["speaker"] = {"name": "44100Hz Null Output"}
info["audio"] = {"name": "Monitor of {}".format(info["speaker"]["name"])}
return info
def create_zip(path):
"""
Takes a `path` on disk and creates a zipfile with its contents. Returns a
path to the location of the temporary zip file.
"""
with tempfile.NamedTemporaryFile() as f:
# `shutil.make_archive` writes to "{f.name}.zip", so we're really just
# using `NamedTemporaryFile` as a way to get a random path.
return shutil.make_archive(f.name, "zip", path)
def update_mozinfo():
"""walk up directories to find mozinfo.json update the info"""
# TODO: This should go in a more generic place, e.g. mozinfo
path = SCRIPT_DIR
dirs = set()
while path != os.path.expanduser("~"):
if path in dirs:
break
dirs.add(path)
path = os.path.split(path)[0]
mozinfo.find_and_update_from_json(*dirs)
class MochitestDesktop(object):
"""
Mochitest class for desktop firefox.
"""
oldcwd = os.getcwd()
# Path to the test script on the server
TEST_PATH = "tests"
CHROME_PATH = "redirect.html"
certdbNew = False
sslTunnel = None
DEFAULT_TIMEOUT = 60.0
mediaDevices = None
mozinfo_variables_shown = False
patternFiles = {}
# XXX use automation.py for test name to avoid breaking legacy
# TODO: replace this with 'runtests.py' or 'mochitest' or the like
test_name = "automation.py"
def __init__(self, flavor, logger_options, staged_addons=None, quiet=False):
update_mozinfo()
self.flavor = flavor
self.staged_addons = staged_addons
self.server = None
self.wsserver = None
self.websocketProcessBridge = None
self.sslTunnel = None
self.manifest = None
self.tests_by_manifest = defaultdict(list)
self.args_by_manifest = defaultdict(set)
self.prefs_by_manifest = defaultdict(set)
self.env_vars_by_manifest = defaultdict(set)
self.tests_dirs_by_manifest = defaultdict(set)
self._active_tests = None
self.currentTests = None
self._locations = None
self.browserEnv = None
self.marionette = None
self.start_script = None
self.mozLogs = None
self.start_script_kwargs = {}
self.extraArgs = []
self.extraPrefs = {}
self.extraEnv = {}
self.extraTestsDirs = []
self.conditioned_profile_dir = None
if logger_options.get("log"):
self.log = logger_options["log"]
else:
self.log = commandline.setup_logging(
"mochitest", logger_options, {"tbpl": sys.stdout}
)
self.message_logger = MessageLogger(
logger=self.log, buffering=quiet, structured=True
)
# Max time in seconds to wait for server startup before tests will fail -- if
# this seems big, it's mostly for debug machines where cold startup
# (particularly after a build) takes forever.
self.SERVER_STARTUP_TIMEOUT = 180 if mozinfo.info.get("debug") else 90
# metro browser sub process id
self.browserProcessId = None
self.haveDumpedScreen = False
# Create variables to count the number of passes, fails, todos.
self.countpass = 0
self.countfail = 0
self.counttodo = 0
self.expectedError = {}
self.result = {}
self.start_script = os.path.join(here, "start_desktop.js")
# Used to temporarily serve a performance profile
self.profiler_tempdir = None
def environment(self, **kwargs):
kwargs["log"] = self.log
return test_environment(**kwargs)
def getFullPath(self, path):
"Get an absolute path relative to self.oldcwd."
return os.path.normpath(os.path.join(self.oldcwd, os.path.expanduser(path)))
def getLogFilePath(self, logFile):
"""return the log file path relative to the device we are testing on, in most cases
it will be the full path on the local system
"""
return self.getFullPath(logFile)
@property
def locations(self):
if self._locations is not None:
return self._locations
locations_file = os.path.join(SCRIPT_DIR, "server-locations.txt")
self._locations = ServerLocations(locations_file)
return self._locations
def buildURLOptions(self, options, env):
"""Add test control options from the command line to the url
URL parameters to test URL:
autorun -- kick off tests automatically
closeWhenDone -- closes the browser after the tests
hideResultsTable -- hides the table of individual test results
logFile -- logs test run to an absolute path
startAt -- name of test to start at
endAt -- name of test to end at
timeout -- per-test timeout in seconds
repeat -- How many times to repeat the test, ie: repeat=1 will run the test twice.
"""
self.urlOpts = []
if not hasattr(options, "logFile"):
options.logFile = ""
if not hasattr(options, "fileLevel"):
options.fileLevel = "INFO"
# allow relative paths for logFile
if options.logFile:
options.logFile = self.getLogFilePath(options.logFile)
if options.flavor in ("a11y", "browser", "chrome"):
self.makeTestConfig(options)
else:
if options.autorun:
self.urlOpts.append("autorun=1")
if options.timeout:
self.urlOpts.append("timeout=%d" % options.timeout)
if options.maxTimeouts:
self.urlOpts.append("maxTimeouts=%d" % options.maxTimeouts)
if not options.keep_open:
self.urlOpts.append("closeWhenDone=1")
if options.logFile:
self.urlOpts.append("logFile=" + encodeURIComponent(options.logFile))
self.urlOpts.append(
"fileLevel=" + encodeURIComponent(options.fileLevel)
)
if options.consoleLevel:
self.urlOpts.append(
"consoleLevel=" + encodeURIComponent(options.consoleLevel)
)
if options.startAt:
self.urlOpts.append("startAt=%s" % options.startAt)
if options.endAt:
self.urlOpts.append("endAt=%s" % options.endAt)
if options.shuffle:
self.urlOpts.append("shuffle=1")
if "MOZ_HIDE_RESULTS_TABLE" in env and env["MOZ_HIDE_RESULTS_TABLE"] == "1":
self.urlOpts.append("hideResultsTable=1")
if options.runUntilFailure:
self.urlOpts.append("runUntilFailure=1")
if options.repeat:
self.urlOpts.append("repeat=%d" % options.repeat)
if len(options.test_paths) == 1 and os.path.isfile(
os.path.join(
self.oldcwd,
os.path.dirname(__file__),
self.TEST_PATH,
options.test_paths[0],
)
):
self.urlOpts.append(
"testname=%s" % "/".join([self.TEST_PATH, options.test_paths[0]])
)
if options.manifestFile:
self.urlOpts.append("manifestFile=%s" % options.manifestFile)
if options.failureFile:
self.urlOpts.append(
"failureFile=%s" % self.getFullPath(options.failureFile)
)
if options.runSlower:
self.urlOpts.append("runSlower=true")
if options.debugOnFailure:
self.urlOpts.append("debugOnFailure=true")
if options.dumpOutputDirectory:
self.urlOpts.append(
"dumpOutputDirectory=%s"
% encodeURIComponent(options.dumpOutputDirectory)
)
if options.dumpAboutMemoryAfterTest:
self.urlOpts.append("dumpAboutMemoryAfterTest=true")
if options.dumpDMDAfterTest:
self.urlOpts.append("dumpDMDAfterTest=true")
if options.debugger or options.jsdebugger:
self.urlOpts.append("interactiveDebugger=true")
if options.jscov_dir_prefix:
self.urlOpts.append("jscovDirPrefix=%s" % options.jscov_dir_prefix)
if options.cleanupCrashes:
self.urlOpts.append("cleanupCrashes=true")
if "MOZ_XORIGIN_MOCHITEST" in env and env["MOZ_XORIGIN_MOCHITEST"] == "1":
options.xOriginTests = True
if options.xOriginTests:
self.urlOpts.append("xOriginTests=true")
if options.comparePrefs:
self.urlOpts.append("comparePrefs=true")
self.urlOpts.append("ignorePrefsFile=ignorePrefs.json")
def normflavor(self, flavor):
"""
In some places the string 'browser-chrome' is expected instead of
'browser' and 'mochitest' instead of 'plain'. Normalize the flavor
strings for those instances.
"""
# TODO Use consistent flavor strings everywhere and remove this
if flavor == "browser":
return "browser-chrome"
elif flavor == "plain":
return "mochitest"
return flavor
def isTest(self, options, filename):
allow_js_css = False
if options.flavor == "browser":
allow_js_css = True
testPattern = re.compile(r"browser_.+\.js")
elif options.flavor in ("a11y", "chrome"):
testPattern = re.compile(r"(browser|test)_.+\.(xul|html|js|xhtml)")
else:
testPattern = re.compile(r"test_")
if not allow_js_css and (".js" in filename or ".css" in filename):
return False
pathPieces = filename.split("/")
return testPattern.match(pathPieces[-1]) and not re.search(
r"\^headers\^$", filename
)
def setTestRoot(self, options):
if options.flavor != "plain":
self.testRoot = options.flavor
else:
self.testRoot = self.TEST_PATH
self.testRootAbs = os.path.join(SCRIPT_DIR, self.testRoot)
def buildTestURL(self, options, scheme="http"):
if scheme == "https":
elif options.xOriginTests:
else:
testURL = "/".join([testHost, self.TEST_PATH])
if len(options.test_paths) == 1:
if os.path.isfile(
os.path.join(
self.oldcwd,
os.path.dirname(__file__),
self.TEST_PATH,
options.test_paths[0],
)
):
testURL = "/".join([testURL, os.path.dirname(options.test_paths[0])])
else:
testURL = "/".join([testURL, options.test_paths[0]])
if options.flavor in ("a11y", "chrome"):
testURL = "/".join([testHost, self.CHROME_PATH])
elif options.flavor == "browser":
testURL = "about:blank"
return testURL
def parseAndCreateTestsDirs(self, m):
testsDirs = list(self.tests_dirs_by_manifest[m])[0]
self.extraTestsDirs = []
if testsDirs:
self.extraTestsDirs = testsDirs.strip().split()
self.log.info(
"The following extra test directories will be created:\n {}".format(
"\n ".join(self.extraTestsDirs)
)
)
self.createExtraTestsDirs(self.extraTestsDirs, m)
def createExtraTestsDirs(self, extraTestsDirs=None, manifest=None):
"""Take a list of directories that might be needed to exist by the test
prior to even the main process be executed, and:
- verify it does not already exists
- create it if it does
Removal of those directories is handled in cleanup()
"""
if type(extraTestsDirs) is not list:
return
for d in extraTestsDirs:
if os.path.exists(d):
raise FileExistsError(
"Directory '{}' already exists. This is a member of "
"test-directories in manifest {}.".format(d, manifest)
)
created = []
for d in extraTestsDirs:
os.makedirs(d)
created += [d]
if created != extraTestsDirs:
raise EnvironmentError(
"Not all directories were created: extraTestsDirs={} -- created={}".format(
extraTestsDirs, created
)
)
def getTestsByScheme(
self, options, testsToFilter=None, disabled=True, manifestToFilter=None
):
"""Build the url path to the specific test harness and test file or directory
Build a manifest of tests to run and write out a json file for the harness to read
testsToFilter option is used to filter/keep the tests provided in the list
disabled -- This allows to add all disabled tests on the build side
and then on the run side to only run the enabled ones
"""
tests = self.getActiveTests(options, disabled)
paths = []
for test in tests:
if testsToFilter and (test["path"] not in testsToFilter):
continue
# If we are running a specific manifest, the previously computed set of active
# tests should be filtered out based on the manifest that contains that entry.
#
# This is especially important when a test file is listed in multiple
# manifests (e.g. because the same test runs under a different configuration,
# and so it is being included in multiple manifests), without filtering the
# active tests based on the current manifest (configuration) that we are
# running for each of the N manifests we would be executing the active tests
# exactly N times (and so NxN runs instead of the expected N runs, one for each
# manifest).
if manifestToFilter and (test["manifest"] not in manifestToFilter):
continue
paths.append(test)
# Generate test by schemes
for scheme, grouped_tests in self.groupTestsByScheme(paths).items():
with open(
os.path.join(SCRIPT_DIR, options.testRunManifestFile), "w"
) as manifestFile:
manifestFile.write(json.dumps({"tests": grouped_tests}))
options.manifestFile = options.testRunManifestFile
yield (scheme, grouped_tests)
def startWebSocketServer(self, options, debuggerInfo):
"""Launch the websocket server"""
self.wsserver = WebSocketServer(options, SCRIPT_DIR, self.log, debuggerInfo)
self.wsserver.start()
def startWebServer(self, options):
"""Create the webserver and start it up"""
self.server = MochitestServer(options, self.log)
self.server.start()
if options.pidFile != "":
with open(options.pidFile + ".xpcshell.pid", "w") as f:
f.write("%s" % self.server._process.pid)
def startWebsocketProcessBridge(self, options):
"""Create a websocket server that can launch various processes that
JS needs (eg; ICE server for webrtc testing)
"""
command = [
sys.executable,
os.path.join("websocketprocessbridge", "websocketprocessbridge.py"),
"--port",
options.websocket_process_bridge_port,
]
self.websocketProcessBridge = subprocess.Popen(command, cwd=SCRIPT_DIR)
self.log.info(
"runtests.py | websocket/process bridge pid: %d"
% self.websocketProcessBridge.pid
)
# ensure the server is up, wait for at most ten seconds
for i in range(1, 100):
if self.websocketProcessBridge.poll() is not None:
self.log.error(
"runtests.py | websocket/process bridge failed "
"to launch. Are all the dependencies installed?"
)
return
try:
sock = socket.create_connection(("127.0.0.1", 8191))
sock.close()
break
except Exception:
time.sleep(0.1)
else:
self.log.error(
"runtests.py | Timed out while waiting for "
"websocket/process bridge startup."
)
def needsWebsocketProcessBridge(self, options):
"""
Returns a bool indicating if the current test configuration needs
to start the websocket process bridge or not. The boils down to if
WebRTC tests that need the bridge are present.
"""
tests = self.getActiveTests(options)
is_webrtc_tag_present = False
for test in tests:
if "webrtc" in test.get("tags", ""):
is_webrtc_tag_present = True
break
return is_webrtc_tag_present and options.subsuite in ["media"]
def startHttp3Server(self, options):
"""
Start a Http3 test server.
"""
http3ServerPath = os.path.join(
options.utilityPath, "http3server" + mozinfo.info["bin_suffix"]
)
serverOptions = {}
serverOptions["http3ServerPath"] = http3ServerPath
serverOptions["profilePath"] = options.profilePath
serverOptions["isMochitest"] = True
serverOptions["isWin"] = mozinfo.isWin
serverOptions["proxyPort"] = options.http3ServerPort
env = test_environment(xrePath=options.xrePath, log=self.log)
serverEnv = env.copy()
serverLog = env.get("MOZHTTP3_SERVER_LOG")
if serverLog is not None:
serverEnv["RUST_LOG"] = serverLog
self.http3Server = Http3Server(serverOptions, serverEnv, self.log)
self.http3Server.start()
port = self.http3Server.ports().get("MOZHTTP3_PORT_PROXY")
if int(port) != options.http3ServerPort:
self.http3Server = None
raise RuntimeError("Error: Unable to start Http/3 server")
def findNodeBin(self):
# We try to find the node executable in the path given to us by the user in
# the MOZ_NODE_PATH environment variable
nodeBin = os.getenv("MOZ_NODE_PATH", None)
self.log.info("Use MOZ_NODE_PATH at %s" % (nodeBin))
if not nodeBin and build:
nodeBin = build.substs.get("NODEJS")
self.log.info("Use build node at %s" % (nodeBin))
return nodeBin
def startHttp2Server(self, options):
"""
Start a Http2 test server.
"""
serverOptions = {}
serverOptions["serverPath"] = os.path.join(
SCRIPT_DIR, "Http2Server", "http2_server.js"
)
serverOptions["nodeBin"] = self.findNodeBin()
serverOptions["isWin"] = mozinfo.isWin
serverOptions["port"] = options.http2ServerPort
env = test_environment(xrePath=options.xrePath, log=self.log)
self.http2Server = Http2Server(serverOptions, env, self.log)
self.http2Server.start()
port = self.http2Server.port()
if port != options.http2ServerPort:
raise RuntimeError("Error: Unable to start Http2 server")
def startDoHServer(self, options, dstServerPort, alpn):
serverOptions = {}
serverOptions["serverPath"] = os.path.join(
SCRIPT_DIR, "DoHServer", "doh_server.js"
)
serverOptions["nodeBin"] = self.findNodeBin()
serverOptions["dstServerPort"] = dstServerPort
serverOptions["isWin"] = mozinfo.isWin
serverOptions["port"] = options.dohServerPort
serverOptions["alpn"] = alpn
env = test_environment(xrePath=options.xrePath, log=self.log)
self.dohServer = DoHServer(serverOptions, env, self.log)
self.dohServer.start()
port = self.dohServer.port()
if port != options.dohServerPort:
raise RuntimeError("Error: Unable to start DoH server")
def startServers(self, options, debuggerInfo, public=None):
# start servers and set ports
# TODO: pass these values, don't set on `self`
self.webServer = options.webServer
self.httpPort = options.httpPort
self.sslPort = options.sslPort
self.webSocketPort = options.webSocketPort
# httpd-path is specified by standard makefile targets and may be specified
# on the command line to select a particular version of httpd.js. If not
# specified, try to select the one from hostutils.zip, as required in
if not options.httpdPath:
options.httpdPath = os.path.join(options.utilityPath, "components")
self.startWebServer(options)
self.startWebSocketServer(options, debuggerInfo)
# Only webrtc mochitests in the media suite need the websocketprocessbridge.
if self.needsWebsocketProcessBridge(options):
self.startWebsocketProcessBridge(options)
# start SSL pipe
self.sslTunnel = SSLTunnel(options, logger=self.log)
self.sslTunnel.buildConfig(self.locations, public=public)
self.sslTunnel.start()
# If we're lucky, the server has fully started by now, and all paths are
# ready, etc. However, xpcshell cold start times suck, at least for debug
# builds. We'll try to connect to the server for awhile, and if we fail,
# we'll try to kill the server and exit with an error.
if self.server is not None:
self.server.ensureReady(self.SERVER_STARTUP_TIMEOUT)
self.log.info("use http3 server: %d" % options.useHttp3Server)
self.http3Server = None
self.http2Server = None
self.dohServer = None
if options.useHttp3Server:
self.startHttp3Server(options)
self.startDoHServer(options, options.http3ServerPort, "h3")
elif options.useHttp2Server:
self.startHttp2Server(options)
self.startDoHServer(options, options.http2ServerPort, "h2")
def stopServers(self):
"""Servers are no longer needed, and perhaps more importantly, anything they
might spew to console might confuse things."""
if self.server is not None:
try:
self.log.info("Stopping web server")
self.server.stop()
except Exception:
self.log.critical("Exception when stopping web server")
if self.wsserver is not None:
try:
self.log.info("Stopping web socket server")
self.wsserver.stop()
except Exception:
self.log.critical("Exception when stopping web socket server")
if self.sslTunnel is not None:
try:
self.log.info("Stopping ssltunnel")
self.sslTunnel.stop()
except Exception:
self.log.critical("Exception stopping ssltunnel")
if self.websocketProcessBridge is not None:
try:
self.websocketProcessBridge.kill()
self.websocketProcessBridge.wait()
self.log.info("Stopping websocket/process bridge")
except Exception:
self.log.critical("Exception stopping websocket/process bridge")
if self.http3Server is not None:
try:
self.http3Server.stop()
except Exception:
self.log.critical("Exception stopping http3 server")
if self.http2Server is not None:
try:
self.http2Server.stop()
except Exception:
self.log.critical("Exception stopping http2 server")
if self.dohServer is not None:
try:
self.dohServer.stop()
except Exception:
self.log.critical("Exception stopping doh server")
if hasattr(self, "gstForV4l2loopbackProcess"):
try:
self.gstForV4l2loopbackProcess.kill()
self.gstForV4l2loopbackProcess.wait()
self.log.info("Stopping gst for v4l2loopback")
except Exception:
self.log.critical("Exception stopping gst for v4l2loopback")
def copyExtraFilesToProfile(self, options):
"Copy extra files or dirs specified on the command line to the testing profile."
for f in options.extraProfileFiles:
abspath = self.getFullPath(f)
if os.path.isfile(abspath):
shutil.copy2(abspath, options.profilePath)
elif os.path.isdir(abspath):
dest = os.path.join(options.profilePath, os.path.basename(abspath))
shutil.copytree(abspath, dest)
else:
self.log.warning("runtests.py | Failed to copy %s to profile" % abspath)
def getChromeTestDir(self, options):
dir = os.path.join(os.path.abspath("."), SCRIPT_DIR) + "/"
if mozinfo.isWin:
return dir
def writeChromeManifest(self, options):
manifest = os.path.join(options.profilePath, "tests.manifest")
with open(manifest, "w") as manifestFile:
# Register chrome directory.
chrometestDir = self.getChromeTestDir(options)
manifestFile.write(
"content mochitests %s contentaccessible=yes\n" % chrometestDir
)
manifestFile.write(
"content mochitests-any %s contentaccessible=yes remoteenabled=yes\n"
% chrometestDir
)
manifestFile.write(
"content mochitests-content %s contentaccessible=yes remoterequired=yes\n"
% chrometestDir
)
if options.testingModulesDir is not None:
manifestFile.write(
)
if options.store_chrome_manifest:
shutil.copyfile(manifest, options.store_chrome_manifest)
return manifest
def addChromeToProfile(self, options):
"Adds MochiKit chrome tests to the profile."
# Create (empty) chrome directory.
chromedir = os.path.join(options.profilePath, "chrome")
os.mkdir(chromedir)
# Write userChrome.css.
chrome = """
/* set default namespace to XUL */
toolbar,
toolbarpalette {
background-color: rgb(235, 235, 235) !important;
}
toolbar#nav-bar {
background-image: none !important;
}
"""
with open(
os.path.join(options.profilePath, "userChrome.css"), "a"
) as chromeFile:
chromeFile.write(chrome)
manifest = self.writeChromeManifest(options)
return manifest
def getExtensionsToInstall(self, options):
"Return a list of extensions to install in the profile"
extensions = []
appDir = (
options.app[: options.app.rfind(os.sep)]
if options.app
else options.utilityPath
)
extensionDirs = [
# Extensions distributed with the test harness.
os.path.normpath(os.path.join(SCRIPT_DIR, "extensions")),
]
if appDir:
# Extensions distributed with the application.
extensionDirs.append(os.path.join(appDir, "distribution", "extensions"))
for extensionDir in extensionDirs:
if os.path.isdir(extensionDir):
for dirEntry in os.listdir(extensionDir):
if dirEntry not in options.extensionsToExclude:
path = os.path.join(extensionDir, dirEntry)
if os.path.isdir(path) or (
os.path.isfile(path) and path.endswith(".xpi")
):
extensions.append(path)
extensions.extend(options.extensionsToInstall)
return extensions
def logPreamble(self, tests):
"""Logs a suite_start message and test_start/test_end at the beginning of a run."""
self.log.suite_start(
self.tests_by_manifest, name="mochitest-{}".format(self.flavor)
)
for test in tests:
if "disabled" in test:
self.log.test_start(test["path"])
self.log.test_end(test["path"], "SKIP", message=test["disabled"])
def loadFailurePatternFile(self, pat_file):
if pat_file in self.patternFiles:
return self.patternFiles[pat_file]
if not os.path.isfile(pat_file):
self.log.warning(
"runtests.py | Cannot find failure pattern file " + pat_file
)
return None
# Using ":error" to ensure it shows up in the failure summary.
self.log.warning(
"[runtests.py:error] Using {} to filter failures. If there "
"is any number mismatch below, you could have fixed "
"something documented in that file. Please reduce the "
"failure count appropriately.".format(pat_file)
)
patternRE = re.compile(
r"""
^\s*\*\s* # list bullet
(test_\S+|\.{3}) # test name
(?:\s*(`.+?`|asserts))? # failure pattern
(?::.+)? # optional description
\s*\[(\d+|\*)\] # expected count
\s*$
""",
re.X,
)
patterns = {}
with open(pat_file) as f:
last_name = None
for line in f:
match = patternRE.match(line)
if not match:
continue
name = match.group(1)
name = last_name if name == "..." else name
last_name = name
pat = match.group(2)
if pat is not None:
pat = "ASSERTION" if pat == "asserts" else pat[1:-1]
count = match.group(3)
count = None if count == "*" else int(count)
if name not in patterns:
patterns[name] = []
patterns[name].append((pat, count))
self.patternFiles[pat_file] = patterns
return patterns
def getFailurePatterns(self, pat_file, test_name):
patterns = self.loadFailurePatternFile(pat_file)
if patterns:
return patterns.get(test_name, None)
def getActiveTests(self, options, disabled=True):
"""
This method is used to parse the manifest and return active filtered tests.
"""
if self._active_tests:
return self._active_tests
tests = []
manifest = self.getTestManifest(options)
if manifest:
if options.extra_mozinfo_json:
mozinfo.update(options.extra_mozinfo_json)
info = mozinfo.info
filters = [
subsuite(options.subsuite),
]
if options.test_tags:
filters.append(tags(options.test_tags))
if options.test_paths:
options.test_paths = self.normalize_paths(options.test_paths)
filters.append(pathprefix(options.test_paths))
# Add chunking filters if specified
if options.totalChunks:
if options.chunkByDir:
filters.append(
chunk_by_dir(
options.thisChunk, options.totalChunks, options.chunkByDir
)
)
elif options.chunkByRuntime:
if mozinfo.info["os"] == "android":
platkey = "android"
elif mozinfo.isWin:
platkey = "windows"
else:
platkey = "unix"
runtime_file = os.path.join(
SCRIPT_DIR,
"runtimes",
"manifest-runtimes-{}.json".format(platkey),
)
if not os.path.exists(runtime_file):
self.log.error("runtime file %s not found!" % runtime_file)
sys.exit(1)
# Given the mochitest flavor, load the runtimes information
with open(runtime_file, "r") as f:
if "suite_name" in options:
runtimes = json.load(f).get(options.suite_name, {})
else:
runtimes = {}
filters.append(
chunk_by_runtime(
options.thisChunk, options.totalChunks, runtimes
)
)
else:
filters.append(
chunk_by_slice(options.thisChunk, options.totalChunks)
)
noDefaultFilters = False
if options.runFailures:
filters.append(failures(options.runFailures))
noDefaultFilters = True
if info["os"] == "mac" and info["os_version"].split(".")[0] == "14":
info["crashreporter"] = False
tests = manifest.active_tests(
exists=False,
disabled=disabled,
filters=filters,
noDefaultFilters=noDefaultFilters,
strictExpressions=True,
**info
)
if len(tests) == 0:
self.log.error(
NO_TESTS_FOUND.format(options.flavor, manifest.fmt_filters())
)
paths = []
for test in tests:
if len(tests) == 1 and "disabled" in test:
del test["disabled"]
pathAbs = os.path.abspath(test["path"])
assert os.path.normcase(pathAbs).startswith(
os.path.normcase(self.testRootAbs)
)
tp = pathAbs[len(self.testRootAbs) :].replace("\\", "/").strip("/")
if not self.isTest(options, tp):
self.log.warning(
"Warning: %s from manifest %s is not a valid test"
% (test["name"], test["manifest"])
)
continue
manifest_key = test["manifest_relpath"]
# Ignore ancestor_manifests that live at the root (e.g, don't have a
# path separator).
if "ancestor_manifest" in test and "/" in normsep(
test["ancestor_manifest"]
):
manifest_key = "{}:{}".format(test["ancestor_manifest"], manifest_key)
manifest_key = manifest_key.replace("\\", "/")
self.tests_by_manifest[manifest_key].append(tp)
self.args_by_manifest[manifest_key].add(test.get("args"))
self.prefs_by_manifest[manifest_key].add(test.get("prefs"))
self.env_vars_by_manifest[manifest_key].add(test.get("environment"))
self.tests_dirs_by_manifest[manifest_key].add(test.get("test-directories"))
for key in ["args", "prefs", "environment", "test-directories"]:
if key in test and not options.runByManifest and "disabled" not in test:
self.log.error(
"parsing {}: runByManifest mode must be enabled to "
"set the `{}` key".format(test["manifest_relpath"], key)
)
sys.exit(1)
testob = {"path": tp, "manifest": manifest_key}
if "disabled" in test:
testob["disabled"] = test["disabled"]
if "expected" in test:
testob["expected"] = test["expected"]
if "https_first_disabled" in test:
testob["https_first_disabled"] = test["https_first_disabled"] == "true"
if "allow_xul_xbl" in test:
testob["allow_xul_xbl"] = test["allow_xul_xbl"] == "true"
if "scheme" in test:
testob["scheme"] = test["scheme"]
if "tags" in test:
testob["tags"] = test["tags"]
if options.failure_pattern_file:
pat_file = os.path.join(
os.path.dirname(test["manifest"]), options.failure_pattern_file
)
patterns = self.getFailurePatterns(pat_file, test["name"])
if patterns:
testob["expected"] = patterns
paths.append(testob)
# The 'args' key needs to be set in the DEFAULT section, unfortunately
# we can't tell what comes from DEFAULT or not. So to validate this, we
# stash all args from tests in the same manifest into a set. If the
# length of the set > 1, then we know 'args' didn't come from DEFAULT.
args_not_default = [
m for m, p in six.iteritems(self.args_by_manifest) if len(p) > 1
]
if args_not_default:
self.log.error(
"The 'args' key must be set in the DEFAULT section of a "
"manifest. Fix the following manifests: {}".format(
"\n".join(args_not_default)
)
)
sys.exit(1)
# The 'prefs' key needs to be set in the DEFAULT section too.
pref_not_default = [
m for m, p in six.iteritems(self.prefs_by_manifest) if len(p) > 1
]
if pref_not_default:
self.log.error(
"The 'prefs' key must be set in the DEFAULT section of a "
"manifest. Fix the following manifests: {}".format(
"\n".join(pref_not_default)
)
)
sys.exit(1)
# The 'environment' key needs to be set in the DEFAULT section too.
env_not_default = [
m for m, p in six.iteritems(self.env_vars_by_manifest) if len(p) > 1
]
if env_not_default:
self.log.error(
"The 'environment' key must be set in the DEFAULT section of a "
"manifest. Fix the following manifests: {}".format(
"\n".join(env_not_default)
)
)
sys.exit(1)
paths.sort(key=lambda p: p["path"].split("/"))
if options.dump_tests:
options.dump_tests = os.path.expanduser(options.dump_tests)
assert os.path.exists(os.path.dirname(options.dump_tests))
with open(options.dump_tests, "w") as dumpFile:
dumpFile.write(json.dumps({"active_tests": paths}))
self.log.info("Dumping active_tests to %s file." % options.dump_tests)
sys.exit()
# Upload a list of test manifests that were executed in this run.
if "MOZ_UPLOAD_DIR" in os.environ:
artifact = os.path.join(os.environ["MOZ_UPLOAD_DIR"], "manifests.list")
with open(artifact, "a") as fh:
fh.write("\n".join(sorted(self.tests_by_manifest.keys())))
self._active_tests = paths
return self._active_tests
def getTestManifest(self, options):
if isinstance(options.manifestFile, TestManifest):
manifest = options.manifestFile
elif options.manifestFile and os.path.isfile(options.manifestFile):
manifestFileAbs = os.path.abspath(options.manifestFile)
assert manifestFileAbs.startswith(SCRIPT_DIR)
manifest = TestManifest([options.manifestFile], strict=False)
elif options.manifestFile and os.path.isfile(
os.path.join(SCRIPT_DIR, options.manifestFile)
):
manifestFileAbs = os.path.abspath(
os.path.join(SCRIPT_DIR, options.manifestFile)
)
assert manifestFileAbs.startswith(SCRIPT_DIR)
manifest = TestManifest([manifestFileAbs], strict=False)
else:
masterName = self.normflavor(options.flavor) + ".toml"
masterPath = os.path.join(SCRIPT_DIR, self.testRoot, masterName)
if not os.path.exists(masterPath):
masterName = self.normflavor(options.flavor) + ".ini"
masterPath = os.path.join(SCRIPT_DIR, self.testRoot, masterName)
if os.path.exists(masterPath):
manifest = TestManifest([masterPath], strict=False)
else:
manifest = None
self.log.warning(
"TestManifest masterPath %s does not exist" % masterPath
)
return manifest
def makeTestConfig(self, options):
"Creates a test configuration file for customizing test execution."
options.logFile = options.logFile.replace("\\", "\\\\")
if (
"MOZ_HIDE_RESULTS_TABLE" in os.environ
and os.environ["MOZ_HIDE_RESULTS_TABLE"] == "1"
):
options.hideResultsTable = True
# strip certain unnecessary items to avoid serialization errors in json.dumps()
d = dict(
(k, v)
for k, v in options.__dict__.items()
if (v is None) or isinstance(v, (six.string_types, numbers.Number))
)
d["testRoot"] = self.testRoot
if options.jscov_dir_prefix:
d["jscovDirPrefix"] = options.jscov_dir_prefix
if not options.keep_open:
d["closeWhenDone"] = "1"
d["runFailures"] = False
if options.runFailures:
d["runFailures"] = True
shutil.copy(
os.path.join(SCRIPT_DIR, "ignorePrefs.json"),
os.path.join(options.profilePath, "ignorePrefs.json"),
)
d["ignorePrefsFile"] = "ignorePrefs.json"
content = json.dumps(d)
with open(os.path.join(options.profilePath, "testConfig.js"), "w") as config:
config.write(content)
def buildBrowserEnv(self, options, debugger=False, env=None):
"""build the environment variables for the specific test and operating system"""
if mozinfo.info["asan"] and mozinfo.isLinux and mozinfo.bits == 64:
useLSan = True
else:
useLSan = False
browserEnv = self.environment(
xrePath=options.xrePath, env=env, debugger=debugger, useLSan=useLSan
)
if options.headless:
browserEnv["MOZ_HEADLESS"] = "1"
if not options.e10s:
browserEnv["MOZ_FORCE_DISABLE_E10S"] = "1"
if options.dmd:
browserEnv["DMD"] = os.environ.get("DMD", "1")
# tests, since some browser-chrome tests test content process crashes;
# also exclude non-e10s since at least one non-e10s mochitest is problematic
if (
options.flavor == "browser" or not options.e10s
) and "MOZ_CRASHREPORTER_SHUTDOWN" in browserEnv:
del browserEnv["MOZ_CRASHREPORTER_SHUTDOWN"]
try:
browserEnv.update(
dict(
parse_key_value(
self.extraEnv, context="environment variable in manifest"
)
)
)
except KeyValueParseError as e:
self.log.error(str(e))
return None
# These variables are necessary for correct application startup; change
# via the commandline at your own risk.
browserEnv["XPCOM_DEBUG_BREAK"] = "stack"
# interpolate environment passed with options
try:
browserEnv.update(
dict(parse_key_value(options.environment, context="--setenv"))
)
except KeyValueParseError as e:
self.log.error(str(e))
return None
if (
"MOZ_PROFILER_STARTUP_FEATURES" not in browserEnv
or "nativeallocations"
not in browserEnv["MOZ_PROFILER_STARTUP_FEATURES"].split(",")
):
# Only turn on the bloat log if the profiler's native allocation feature is
# not enabled. The two are not compatible.
browserEnv["XPCOM_MEM_BLOAT_LOG"] = self.leak_report_file
# If profiling options are enabled, turn on the gecko profiler by using the
# profiler environmental variables.
if options.profiler:
# The user wants to capture a profile, and automatically view it. The
# profile will be saved to a temporary folder, then deleted after
# opening in profiler.firefox.com.
self.profiler_tempdir = tempfile.mkdtemp()
browserEnv["MOZ_PROFILER_SHUTDOWN"] = os.path.join(
self.profiler_tempdir, "mochitest-profile.json"
)
browserEnv["MOZ_PROFILER_STARTUP"] = "1"
if options.profilerSaveOnly:
# The user wants to capture a profile, but only to save it. This defaults
# to the MOZ_UPLOAD_DIR.
browserEnv["MOZ_PROFILER_STARTUP"] = "1"
if "MOZ_UPLOAD_DIR" in browserEnv:
browserEnv["MOZ_PROFILER_SHUTDOWN"] = os.path.join(