<commit_before>#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Generate and process code coverage.

TODO(jrg): rename this from coverage_posix.py to coverage_all.py!

Written for and tested on Mac, Linux, and Windows.  To use this script
to generate coverage numbers, please run from within a gyp-generated
project.

All platforms, to set up coverage:
  cd ...../chromium ; src/tools/gyp/gyp_dogfood -Dcoverage=1 src/build/all.gyp

Run coverage on...
Mac:
  ( cd src/chrome ; xcodebuild -configuration Debug -target coverage )
Linux:
  ( cd src/chrome ; hammer coverage )
  # In particular, don't try and run 'coverage' from src/build


--directory=DIR: specify directory that contains gcda files, and where
  a "coverage" directory will be created containing the output html.
  Example name:   ..../chromium/src/xcodebuild/Debug.
  If not specified (e.g. buildbot) we will try and figure it out based on
  other options (e.g. --target and --build-dir; see below).

--genhtml: generate html output.  If not specified only lcov is generated.

--all_unittests: if present, run all files named *_unittests that we
  can find.

--fast_test: make the tests run real fast (just for testing)

--strict: if a test fails, we continue happily.  --strict will cause
  us to die immediately.

--trim=False: by default we trim away tests known to be problematic on
  specific platforms.  If set to false we do NOT trim out tests.

--xvfb=True: By default we use Xvfb to make sure DISPLAY is valid
  (Linux only).  if set to False, do not use Xvfb.  TODO(jrg): convert
  this script from the compile stage of a builder to a
  RunPythonCommandInBuildDir() command to avoid the need for this
  step.

--timeout=SECS: if a subprocess doesn't have output within SECS,
  assume it's a hang.  Kill it and give up.

--bundles=BUNDLEFILE: a file containing a python list of coverage
  bundles to be eval'd.  Example contents of the bundlefile:
    ['../base/base.gyp:base_unittests']
  This is used as part of the coverage bot.
  If no other bundlefile-finding args are used (--target,
  --build-dir), this is assumed to be an absolute path.
  If those args are used, find BUNDLEFILE in a way consistent with
  other scripts launched by buildbot.  Example of another script
  launched by buildbot:
  http://src.chromium.org/viewvc/chrome/trunk/tools/buildbot/scripts/slave/runtest.py

--target=NAME: specify the build target (e.g. 'Debug' or 'Release').
  This is used by buildbot scripts to help us find the output directory.
  Must be used with --build-dir.

--build-dir=DIR: According to buildbot comments, this is the name of
  the directory within the buildbot working directory in which the
  solution, Debug, and Release directories are found.
  It's usually "src/build", but on mac it's $DIR/../xcodebuild and on
  Linux it's $DIR/out.
  This is used by buildbot scripts to help us find the output directory.
  Must be used with --target.

--no_exclusions: Do NOT use the exclusion list.  This script keeps a
  list of tests known to be problematic under coverage.  For example,
  ProcessUtilTest.SpawnChild will crash inside __gcov_fork() when
  using the MacOS 10.6 SDK.  Use of --no_exclusions prevents the use
  of this exclusion list.

--dont-clear-coverage-data: Normally we clear coverage data from
  previous runs.  If this arg is used we do NOT clear the coverage
  data.

Strings after all options are considered tests to run.  Test names
have all text before a ':' stripped to help with gyp compatibility.
For example, ../base/base.gyp:base_unittests is interpreted as a test
named "base_unittests".
"""

import glob
import logging
import optparse
import os
import Queue
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback


"""Global list of child PIDs to kill when we die."""
gChildPIDs = []

"""Exclusion list.  Format is
   { platform: { testname: (exclusion1, exclusion2, ... ), ... } }

   Platform is a match for sys.platform and can be a list.
   Matching code does an 'if sys.platform in (the key):'.
   Similarly, matching does an 'if testname in thefulltestname:'

   The Chromium convention has traditionally been to place the
   exclusion list in a distinct file.  Unlike valgrind (which has
   frequent changes when things break and are fixed), the expectation
   here is that exclusions remain relatively constant (e.g. OS bugs).
   If that changes, revisit the decision to place inclusions in this
   script.

   Details:
     ProcessUtilTest.SpawnChild: chokes in __gcov_fork on 10.6
     IPCFuzzingTest.MsgBadPayloadArgs: ditto
"""
gTestExclusions = {
  'darwin2': { 'base_unittests': ('ProcessUtilTest.SpawnChild',),
               'ipc_tests': ('IPCFuzzingTest.MsgBadPayloadArgs',), }
}


def TerminateSignalHandler(sig, stack):
  """When killed, try and kill our child processes."""
  signal.signal(sig, signal.SIG_DFL)
  for pid in gChildPIDs:
    if 'kill' in os.__all__:  # POSIX
      os.kill(pid, sig)
    else:
      subprocess.call(['taskkill.exe', '/PID', str(pid)])
  sys.exit(0)


class RunTooLongException(Exception):
  """Thrown when a command runs too long without output."""
  pass

class BadUserInput(Exception):
  """Thrown when arguments from the user are incorrectly formatted."""
  pass


class RunProgramThread(threading.Thread):
  """A thread to run a subprocess.

  We want to print the output of our subprocess in real time, but also
  want a timeout if there has been no output for a certain amount of
  time.  Normal techniques (e.g. loop in select()) aren't cross<commit_msg>FullscreenControllerTests fail on coverage bots thereby aborting the test. Skipping these tests when running browser_tests.<commit_after>#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

"""Generate and process code coverage.

TODO(jrg): rename this from coverage_posix.py to coverage_all.py!

Written for and tested on Mac, Linux, and Windows.  To use this script
to generate coverage numbers, please run from within a gyp-generated
project.

All platforms, to set up coverage:
  cd ...../chromium ; src/tools/gyp/gyp_dogfood -Dcoverage=1 src/build/all.gyp

Run coverage on...
Mac:
  ( cd src/chrome ; xcodebuild -configuration Debug -target coverage )
Linux:
  ( cd src/chrome ; hammer coverage )
  # In particular, don't try and run 'coverage' from src/build


--directory=DIR: specify directory that contains gcda files, and where
  a "coverage" directory will be created containing the output html.
  Example name:   ..../chromium/src/xcodebuild/Debug.
  If not specified (e.g. buildbot) we will try and figure it out based on
  other options (e.g. --target and --build-dir; see below).

--genhtml: generate html output.  If not specified only lcov is generated.

--all_unittests: if present, run all files named *_unittests that we
  can find.

--fast_test: make the tests run real fast (just for testing)

--strict: if a test fails, we continue happily.  --strict will cause
  us to die immediately.

--trim=False: by default we trim away tests known to be problematic on
  specific platforms.  If set to false we do NOT trim out tests.

--xvfb=True: By default we use Xvfb to make sure DISPLAY is valid
  (Linux only).  if set to False, do not use Xvfb.  TODO(jrg): convert
  this script from the compile stage of a builder to a
  RunPythonCommandInBuildDir() command to avoid the need for this
  step.

--timeout=SECS: if a subprocess doesn't have output within SECS,
  assume it's a hang.  Kill it and give up.

--bundles=BUNDLEFILE: a file containing a python list of coverage
  bundles to be eval'd.  Example contents of the bundlefile:
    ['../base/base.gyp:base_unittests']
  This is used as part of the coverage bot.
  If no other bundlefile-finding args are used (--target,
  --build-dir), this is assumed to be an absolute path.
  If those args are used, find BUNDLEFILE in a way consistent with
  other scripts launched by buildbot.  Example of another script
  launched by buildbot:
  http://src.chromium.org/viewvc/chrome/trunk/tools/buildbot/scripts/slave/runtest.py

--target=NAME: specify the build target (e.g. 'Debug' or 'Release').
  This is used by buildbot scripts to help us find the output directory.
  Must be used with --build-dir.

--build-dir=DIR: According to buildbot comments, this is the name of
  the directory within the buildbot working directory in which the
  solution, Debug, and Release directories are found.
  It's usually "src/build", but on mac it's $DIR/../xcodebuild and on
  Linux it's $DIR/out.
  This is used by buildbot scripts to help us find the output directory.
  Must be used with --target.

--no_exclusions: Do NOT use the exclusion list.  This script keeps a
  list of tests known to be problematic under coverage.  For example,
  ProcessUtilTest.SpawnChild will crash inside __gcov_fork() when
  using the MacOS 10.6 SDK.  Use of --no_exclusions prevents the use
  of this exclusion list.

--dont-clear-coverage-data: Normally we clear coverage data from
  previous runs.  If this arg is used we do NOT clear the coverage
  data.

Strings after all options are considered tests to run.  Test names
have all text before a ':' stripped to help with gyp compatibility.
For example, ../base/base.gyp:base_unittests is interpreted as a test
named "base_unittests".
"""

import glob
import logging
import optparse
import os
import Queue
import re
import shutil
import signal
import subprocess
import sys
import tempfile
import threading
import time
import traceback


"""Global list of child PIDs to kill when we die."""
gChildPIDs = []

"""Exclusion list.  Format is
   { platform: { testname: (exclusion1, exclusion2, ... ), ... } }

   Platform is a match for sys.platform and can be a list.
   Matching code does an 'if sys.platform in (the key):'.
   Similarly, matching does an 'if testname in thefulltestname:'

   The Chromium convention has traditionally been to place the
   exclusion list in a distinct file.  Unlike valgrind (which has
   frequent changes when things break and are fixed), the expectation
   here is that exclusions remain relatively constant (e.g. OS bugs).
   If that changes, revisit the decision to place inclusions in this
   script.

   Details:
     ProcessUtilTest.SpawnChild: chokes in __gcov_fork on 10.6
     IPCFuzzingTest.MsgBadPayloadArgs: ditto
     FullscreenControllerTest.*: Fails on coverage bots thereby
     aborting the test.
"""
gTestExclusions = {
  'darwin2': { 'base_unittests': ('ProcessUtilTest.SpawnChild',),
               'ipc_tests': ('IPCFuzzingTest.MsgBadPayloadArgs',), },
  'linux2': { 'browser_tests': ('*FullscreenControllerTest.*',), },
}


def TerminateSignalHandler(sig, stack):
  """When killed, try and kill our child processes."""
  signal.signal(sig, signal.SIG_DFL)
  for pid in gChildPIDs:
    if 'kill' in os.__all__:  # POSIX
      os.kill(pid, sig)
    else:
      subprocess.call(['taskkill.exe', '/PID', str(pid)])
  sys.exit(0)


class RunTooLongException(Exception):
  """Thrown when a command runs too long without output."""
  pass

class BadUserInput(Exception):
  """Thrown when arguments from the user are incorrectly formatted."""
  pass


class RunProgramThread(threading.Thread):
  """A thread to run a subprocess.

  We want to print the output of our subprocess in real time, but also
  want a timeout if there has been no output for a certain amount of
  time.  Normal techniques (e.g. loop in select()) aren't cross
{'fraction_non_alphanumeric': 0.08129735251553588, 'fraction_numerical': 0.002638971652336767, 'mean_word_length': 3.654516640253566, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3937610', 'n_tokens_mistral': 3496, 'n_tokens_neox': 3397, 'n_words': 1565}