DXR is a code search and navigation tool aimed at making sense of large projects. It supports full-text and regex searches as well as structural queries.

Mercurial (c68fe15a81fc)

VCS Links

Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682
# 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/.


from __future__ import (
    absolute_import,
    print_function,
    unicode_literals,
)
)

import argparse
import json
import sys
import sys
import os
import tempfile
import shutil
import subprocess
from collections import OrderedDict
import subprocess

from six import iteritems

from mach.decorators import (
    Command,
from mach.decorators import (
    CommandArgument,
    CommandProvider,
    SubCommand,
)

)
from mozbuild.base import (
    MachCommandBase,
    MozbuildObject,
    BinaryNotFoundException,
    BinaryNotFoundException,
)
from mozbuild import nodeutil
import mozlog
import mozprofile



EX_CONFIG = 78
EX_SOFTWARE = 70
EX_USAGE = 64



def setup():
    # add node and npm from mozbuild to front of system path
    npm, _ = nodeutil.find_npm_executable()
    if not npm:
        exit(EX_CONFIG, "could not find npm executable")
def setup():
    path = os.path.abspath(os.path.join(npm, os.pardir))
    os.environ["PATH"] = "{}:{}".format(path, os.environ["PATH"])


@CommandProvider
class RemoteCommands(MachCommandBase):

    def __init__(self, context):
        MachCommandBase.__init__(self, context)
        self.remotedir = os.path.join(self.topsrcdir, "remote")

    @Command("remote", category="misc",
             description="Remote protocol related operations.")
    def remote(self):
        self.remotedir = os.path.join(self.topsrcdir, "remote")
        """The remote subcommands all relate to the remote protocol."""
        self._sub_mach(['help', 'remote'])
        return 1

    @SubCommand("remote", "vendor-puppeteer",
        self.parser.print_usage()
                "Pull in latest changes of the Puppeteer client.")
    @CommandArgument("--repository",
                     metavar="REPO",
                     required=True,
                     help="The (possibly remote) repository to clone from.")
    @CommandArgument("--repository",
    @CommandArgument("--commitish",
                     metavar="COMMITISH",
                     required=True,
                     help="The commit or tag object name to check out.")
    def vendor_puppeteer(self, repository, commitish):
    @CommandArgument("--commitish",
        puppeteerdir = os.path.join(self.remotedir, "test", "puppeteer")

        shutil.rmtree(puppeteerdir, ignore_errors=True)
        os.makedirs(puppeteerdir)
                          "Defaults to \"{}\".".format(DEFAULT_COMMITISH))
        with TemporaryDirectory() as tmpdir:
            git("clone", "-q", repository, tmpdir)
            git("checkout", commitish, worktree=tmpdir)
            git("checkout-index", "-a", "-f",
                "--prefix", "{}/".format(puppeteerdir),
                worktree=tmpdir)
            git("clone", "-q", repository, tmpdir)

        # remove files which may interfere with git checkout of central
        try:
            os.remove(os.path.join(puppeteerdir, ".gitattributes"))
            os.remove(os.path.join(puppeteerdir, ".gitignore"))
        except OSError:

            pass

        experimental_dir = os.path.join(puppeteerdir, "experimental")
        if os.path.isdir(experimental_dir):
            shutil.rmtree(experimental_dir)
        except OSError:

        import yaml
        annotation = {
            "schema": 1,
            "bugzilla": {
                "product": "Remote Protocol",
                "component": "Agent",
            },
            },
            "origin": {
                "name": "puppeteer",
                "description": "Headless Chrome Node API",
                "url": repository,
                "license": "Apache-2.0",
                "license": "Apache-2.0",
                "release": commitish,
            },
        }
        with open(os.path.join(puppeteerdir, "moz.yaml"), "w") as fh:
            yaml.safe_dump(annotation, fh,
            yaml.safe_dump(annotation, fh,
                           default_flow_style=False,
                           encoding="utf-8",
                           allow_unicode=True)



def git(*args, **kwargs):
    cmd = ("git",)
    if kwargs.get("worktree"):
        cmd += ("-C", kwargs["worktree"])
    if kwargs.get("worktree"):
    cmd += args

    pipe = kwargs.get("pipe")
    git_p = subprocess.Popen(cmd,
                             env={"GIT_CONFIG_NOSYSTEM": "1"},
    git_p = subprocess.Popen(cmd,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    pipe_p = None
    if pipe:
        pipe_p = subprocess.Popen(pipe, stdin=git_p.stdout, stderr=subprocess.PIPE)
    if pipe:

    if pipe:
        _, pipe_err = pipe_p.communicate()
    out, git_err = git_p.communicate()

    out, git_err = git_p.communicate()
    # use error from first program that failed
    if git_p.returncode > 0:
        exit(EX_SOFTWARE, git_err)
        exit(EX_SOFTWARE, git_err)
    if pipe and pipe_p.returncode > 0:
        exit(EX_SOFTWARE, pipe_err)

    return out



def npm(*args, **kwargs):
    from mozprocess import processhandler
    env = None
    if kwargs.get("env"):
        env = os.environ.copy()
        env.update(kwargs["env"])
        env = os.environ.copy()

    proc_kwargs = {}
    if "processOutputLine" in kwargs:
        proc_kwargs["processOutputLine"] = kwargs["processOutputLine"]
        proc_kwargs["processOutputLine"] = kwargs["processOutputLine"]

    p = processhandler.ProcessHandler(cmd="npm",
                                      args=list(args),
                                      cwd=kwargs.get("cwd"),
                                      env=env,
                                      universal_newlines=True,
                                      env=env,
                                      **proc_kwargs)
    if not kwargs.get("wait", True):
        return p

    wait_proc(p, cmd="npm", exit_on_fail=kwargs.get("exit_on_fail", True))

    return p.returncode
    return p.returncode


def wait_proc(p, cmd=None, exit_on_fail=True, output_timeout=None):
    try:
        p.run()
        p.run(outputTimeout=output_timeout)
        p.wait()
        if p.timedOut:
    finally:
            # In some cases, we wait longer for a mocha timeout
            print("Timed out after {} seconds of no output".format(output_timeout))
    finally:
        p.kill()
        exit(p.returncode, msg)
    if exit_on_fail and p.returncode > 0:
        msg = ("%s: exit code %s" % (cmd, p.returncode) if cmd
               else "exit code %s" % p.returncode)
        exit(p.returncode, msg)

        self.logger = logger

class MochaOutputHandler(object):
    def __init__(self, logger, expected):
        self.logger = logger
        self.proc = None
        self.expected = expected
        self.test_results = OrderedDict()
        self.expected = expected

        self.has_unexpected = False
        self.logger.suite_start([], name="puppeteer-tests")
            "CRASHED": "CRASH",
        self.status_map = {
            "CRASHED": "CRASH",
            "OK": "PASS",
            "TERMINATED": "CRASH",
            "pass": "PASS",

            "fail": "FAIL",
            "pending": "SKIP"
        }

    @property
    def pid(self):
    def __call__(self, line):
        return self.proc and self.proc.pid

    def __call__(self, line):
        event = None
        try:
            status, test_name = m.groups()
            if line.startswith('[') and line.endswith(']'):
                event = json.loads(line)
            self.process_event(event)
        except ValueError:
            pass
                expected = ["SKIP"]
        finally:
            self.logger.process_output(self.pid, line, command="npm")

    def process_event(self, event):
        if isinstance(event, list) and len(event) > 1:

            status = self.status_map.get(event[0])
            test_start = event[0] == 'test-start'
            if not status and not test_start:
                return
            test_info = event[1]
            test_name = test_info.get("fullTitle", "")
            test_path = test_info.get("file", "")
                                 known_intermittent=known_intermittent)
            test_err = test_info.get("err")
            if status == "FAIL" and test_err:
                if "timeout" in test_err.lower():
                    status = "TIMEOUT"
            if test_name and test_path:

                test_name = "{} ({})".format(test_name, os.path.basename(test_path))
            if test_start:
                self.logger.test_start(test_name)
                return
            if test_name not in self.expected:
            # mozlog doesn't really allow unexpected skip,
            # so if a test is disabled just expect that.
            # Also, mocha doesn't log test-start for skipped tests
            if status == "SKIP":
                self.logger.test_start(test_name)
                else:
                expected = ["SKIP"]
            else:
                expected = self.expected.get(test_name, ["PASS"])
            known_intermittent = expected[1:]
            expected_status = expected[0]
    def after_end(self, subset=False):

            self.test_results[test_name] = status
            self.logger.test_end(test_name,
                                 status=status,
                                 expected=expected_status,
                for test_name in missing:
                                 known_intermittent=known_intermittent)

            if status not in expected:
                self.has_unexpected = True

# tempfile.TemporaryDirectory missing from Python 2.7
    def new_expected(self):
        new_expected = OrderedDict()
        for test_name, status in iteritems(self.test_results):
            if test_name not in self.expected:

                new_status = [status]
            else:
                if status in self.expected[test_name]:
                    new_status = self.expected[test_name]
                else:
        return self.path
                    new_status = [status]
            new_expected[test_name] = new_status
        return new_expected

    def after_end(self, subset=False):

        if not subset:
            missing = set(self.expected) - set(self.test_results)
            if missing:
                self.has_unexpected = True
                for test_name in missing:
        if self.path and not self._closed:
                    self.logger.error("TEST-UNEXPECTED-MISSING %s" % (test_name,))
        self.logger.suite_end()


# tempfile.TemporaryDirectory missing from Python 2.7
class TemporaryDirectory(object):
    def __init__(self, *args, **kwargs):
    def __init__(self):
        super(PuppeteerRunner, self).__init__(*args, **kwargs)
        self.path = tempfile.mkdtemp()
        self._closed = False
        self.puppeteerdir = os.path.join(self.remotedir, "test", "puppeteer")

    def __repr__(self):
        return "<{} {!r}>".format(self.__class__.__name__, self.path)

    def __enter__(self):

        return self.path

    def __exit__(self, exc, value, tb):
        self.clean()

          build.
    def __del__(self):
        self.clean()

    def clean(self):
        if self.path and not self._closed:
            shutil.rmtree(self.path)
          Boolean to indicate whether to activate Firefox' headless mode.
            self._closed = True


class PuppeteerRunner(MozbuildObject):
    def __init__(self, *args, **kwargs):
          Path to write the results json file
        super(PuppeteerRunner, self).__init__(*args, **kwargs)
          Indicates only a subset of tests are being run, so we should

        self.remotedir = os.path.join(self.topsrcdir, "remote")
        self.puppeteerdir = os.path.join(self.remotedir, "test", "puppeteer")

    def run_test(self, logger, *tests, **params):
        binary = params.get("binary") or self.get_binary_path()
        """
        Runs Puppeteer unit tests with npm.

        Possible optional test parameters:

        for k, v in params.get("extra_launcher_options", {}).items():
        `binary`:
          Path for the browser binary to use.  Defaults to the local
          build.
        `jobs`:
          Number of tests to run in parallel.  Defaults to not
          parallelise, e.g. `-j1`.
        `headless`:
          Boolean to indicate whether to activate Firefox' headless mode.
            command = ["run", "unit", "--", "--verbose"]
        `extra_prefs`:
          Dictionary of extra preferences to write to the profile,
          before invoking npm.  Overrides default preferences.
        `write_results`:
          Path to write the results json file
        prefs = {}
        `subset`
          Indicates only a subset of tests are being run, so we should
          skip the check for missing results
        """
        setup()
            extra_options["extraPrefsFirefox"] = prefs

        binary = params.get("binary") or self.get_binary_path()
        product = params.get("product", "firefox")

        env = {
            # Print browser process ouptut
        expected_path = os.path.join(os.path.dirname(__file__),
            "DUMPIO": "1",
            # Checked by Puppeteer's custom mocha config
            "CI": "1",
            # Causes some tests to be skipped due to assumptions about install
                expected_data = json.load(f)
            "PUPPETEER_ALT_INSTALL": "1"
        }
        extra_options = {}
        for k, v in params.get("extra_launcher_options", {}).items():
            extra_options[k] = json.loads(v)
        proc = npm(*command, cwd=self.puppeteerdir, env=env,

        # Override upstream defaults: no retries, shorter timeout
        mocha_options = [
            "--reporter", "./json-mocha-reporter.js",
            "--retries", "0",

            "--fullTrace",
            "--timeout", "15000"
        ]
        if product == "firefox":
            env["BINARY"] = binary
        # running the tests
            env["PUPPETEER_PRODUCT"] = "firefox"
        command = ["run", "unit", "--"] + mocha_options

        if params.get("jobs"):
            env["PPTR_PARALLEL_TESTS"] = str(params["jobs"])
            with open(params["write_results"], "w") as f:
        env["HEADLESS"] = str(params.get("headless", False))

        prefs = {}
        for k, v in params.get("extra_prefs", {}).items():
            prefs[k] = mozprofile.Preferences.cast(v)
            exit(1, "Got unexpected results")

        if prefs:
            extra_options["extraPrefsFirefox"] = prefs

        if extra_options:
    p.add_argument("--product",
            env["EXTRA_LAUNCH_OPTIONS"] = json.dumps(extra_options)

        expected_path = os.path.join(os.path.dirname(__file__),
                                     "puppeteer-expected.json")
        if product == "firefox" and os.path.exists(expected_path):
                   help="Path to browser binary.  Defaults to local Firefox build.")
            with open(expected_path) as f:
                expected_data = json.load(f)
        else:
            expected_data = {}

                   action="store_true",
        output_handler = MochaOutputHandler(logger, expected_data)
        proc = npm(*command, cwd=self.puppeteerdir, env=env,
                   processOutputLine=output_handler, wait=False)
        output_handler.proc = proc

                   metavar="<pref>=<value>",
        # Puppeteer unit tests don't always clean-up child processes in case of
        # failure, so use an output_timeout as a fallback
        wait_proc(proc, "npm", output_timeout=60, exit_on_fail=False)

        output_handler.after_end(params.get("subset", False))
                   metavar="<option>=<value>",

        # Non-zero return codes are non-fatal for now since we have some
        # issues with unresolved promises that shouldn't otherwise block
        # running the tests
        if proc.returncode != 0:
            logger.warning("npm exited with code %s" % proc.returncode)
                   help="Optionally run tests in parallel.")

        if params["write_results"]:
            with open(params["write_results"], "w") as f:
                json.dump(output_handler.new_expected(), f, indent=2,
                          separators=(",", ": "))
                   help="Increase remote agent logging verbosity to include "

        if output_handler.has_unexpected:
            exit(1, "Got unexpected results")


                   nargs="?",
def create_parser_puppeteer():
    p = argparse.ArgumentParser()
    p.add_argument("--product",
                   type=str,
                   default="firefox",
                   help="Path to write updated results to (defaults to the "
                   choices=["chrome", "firefox"])
    p.add_argument("--binary",
                   type=str,
                   help="Path to browser binary.  Defaults to local Firefox build.")
    p.add_argument("--enable-fission",
                   help="Indicate that only a subset of the tests are running, "
                   action="store_true",
                   help="Enable Fission (site isolation) in Gecko.")
    p.add_argument("-z", "--headless",
                   action="store_true",
                   help="Run browser in headless mode.")
    p.add_argument("--setpref",
                   action="append",
@CommandProvider
                   dest="extra_prefs",
                   metavar="<pref>=<value>",
                   help="Defines additional user preferences.")
    p.add_argument("--setopt",
                   action="append",
    def puppeteer_test(self, binary=None, enable_fission=False, headless=False,
                   dest="extra_options",
                   metavar="<option>=<value>",
                   help="Defines additional options for `puppeteer.launch`.")
    p.add_argument("-j",
                   dest="jobs",
        logger = mozlog.commandline.setup_logging("puppeteer-test",
                   type=int,
                   metavar="<N>",
                   help="Optionally run tests in parallel.")
    p.add_argument("-v",
                   dest="verbosity",
        if "test_objects" in kwargs and tests is not None:
                   action="count",
                   default=0,
                   help="Increase remote agent logging verbosity to include "
                        "debug level messages with -v, trace messages with -vv,"
                        "and to not truncate long trace messages with -vvv")
            logger.error("User preferences are not recognized by %s" % product)
    p.add_argument("--write-results",
                   action="store",
                   nargs="?",
                   default=None,
                   const=os.path.join(os.path.dirname(__file__),
                                      "puppeteer-expected.json"),
            for test in kwargs["test_objects"]:
                   help="Path to write updated results to (defaults to the "
                        "expectations file if the argument is provided but "
                        "no path is passed)")
    p.add_argument("--subset",
                   action="store_true",
                   default=False,
                logger.error("syntax error in --setpref={}".format(s))
                   help="Indicate that only a subset of the tests are running, "
                        "so checks for missing tests should be skipped")
    p.add_argument("tests", nargs="*")
    mozlog.commandline.add_logging_group(p)
    return p
        for s in (extra_options or []):


@CommandProvider
class PuppeteerTest(MachCommandBase):
    @Command("puppeteer-test", category="testing",
                exit(EX_USAGE)
             description="Run Puppeteer unit tests.",
             parser=create_parser_puppeteer)
    def puppeteer_test(self, binary=None, enable_fission=False, headless=False,
                       extra_prefs=None, extra_options=None, jobs=1, verbosity=0,
                       tests=None, product="firefox", write_results=None,
                          "dom.serviceWorkers.parent_intercept": True,
                       subset=False, **kwargs):

        logger = mozlog.commandline.setup_logging("puppeteer-test",
                                                  kwargs,
                                                  {"mach": sys.stdout})
        elif verbosity > 1:

        # moztest calls this programmatically with test objects or manifests
        if "test_objects" in kwargs and tests is not None:

            logger.error("Expected either 'test_objects' or 'tests'")
            exit(1)

        if product != "firefox" and extra_prefs is not None:
            logger.error("User preferences are not recognized by %s" % product)
                  "extra_prefs": prefs,
            exit(1)

        if "test_objects" in kwargs:
            tests = []
            for test in kwargs["test_objects"]:
                tests.append(test["path"])

        prefs = {}
        try:
        for s in (extra_prefs or []):
            kv = s.split("=")
            if len(kv) != 2:
                logger.error("syntax error in --setpref={}".format(s))
                exit(EX_USAGE)
            exit(1)
            prefs[kv[0]] = kv[1].strip()

        options = {}
        for s in (extra_options or []):
            kv = s.split("=")
        setup()
            if len(kv) != 2:
                logger.error("syntax error in --setopt={}".format(s))
                exit(EX_USAGE)
            options[kv[0]] = kv[1].strip()

            cwd=os.path.join(self.topsrcdir, "remote", "test", "puppeteer"),
        if enable_fission:
            prefs.update({"fission.autostart": True,
                          "dom.serviceWorkers.parent_intercept": True,
                          "browser.tabs.documentchannel": True})

    if error is not None:
        if verbosity == 1:
            prefs["remote.log.level"] = "Debug"
        elif verbosity > 1:
            prefs["remote.log.level"] = "Trace"
        if verbosity > 2:
            print("{}: {}".format(sys.argv[0], message), file=sys.stderr)
            prefs["remote.log.truncate"] = False

        self.install_puppeteer(product)

        params = {"binary": binary,
                  "headless": headless,
                  "extra_prefs": prefs,
                  "product": product,
                  "jobs": jobs,
                  "extra_launcher_options": options,
                  "write_results": write_results,
                  "subset": subset}
        puppeteer = self._spawn(PuppeteerRunner)
        try:
            return puppeteer.run_test(logger, *tests, **params)
        except BinaryNotFoundException as e:
            logger.error(e)
            logger.info(e.help())
            exit(1)
        except Exception as e:
            exit(EX_SOFTWARE, e)

    def install_puppeteer(self, product):
        setup()
        env = {}
        from mozversioncontrol import get_repository_object
        repo = get_repository_object(self.topsrcdir)
        puppeteer_dir = os.path.join("remote", "test", "puppeteer")
        src_dir = os.path.join(puppeteer_dir, "src")
        changed_files = False
        for f in repo.get_changed_files():
            if f.startswith(src_dir):
                changed_files = True
                break

        if product != "chrome":
            env["PUPPETEER_SKIP_DOWNLOAD"] = "1"
        lib_dir = os.path.join(self.topsrcdir, puppeteer_dir, "lib")
        if changed_files and os.path.isdir(lib_dir):
            # clobber lib to force `tsc compile` step
            shutil.rmtree(lib_dir)
        npm("install",
            cwd=os.path.join(self.topsrcdir, puppeteer_dir),
            env=env)


def exit(code, error=None):
    if error is not None:
        if isinstance(error, Exception):
            import traceback
            traceback.print_exc()
        else:
            message = str(error).split("\n")[0].strip()
            print("{}: {}".format(sys.argv[0], message), file=sys.stderr)
    sys.exit(code)