예제 #1
0
 def test_sort_report_by_invalid_option(self):
     # Sort the text report by a nonsense column.
     opts = CoverageConfig()
     opts.from_args(sort='Xyzzy')
     msg = "Invalid sorting option: 'Xyzzy'"
     with self.assertRaisesRegex(CoverageException, msg):
         self.get_summary_text(opts)
예제 #2
0
    def test_test_data(self):
        # We use our own test files as test data. Check that our assumptions
        # about them are still valid.  We want the three columns of numbers to
        # sort in three different orders.
        data = self.get_coverage_data(self.LINES_1)
        report = self.get_summary_text(data, CoverageConfig())
        print(report)
        # Name                     Stmts   Miss  Cover
        # --------------------------------------------
        # tests/test_api.py          339    155    54%
        # tests/test_backward.py      13      3    77%
        # tests/test_coverage.py     234    228     3%
        # --------------------------------------------
        # TOTAL                      586    386    34%

        lines = report.splitlines()[2:-2]
        self.assertEqual(len(lines), 3)
        nums = [list(map(int, l.replace('%', '').split()[1:])) for l in lines]
        # [
        #  [339, 155, 54],
        #  [ 13,   3, 77],
        #  [234, 228,  3]
        # ]
        self.assertTrue(nums[1][0] < nums[2][0] < nums[0][0])
        self.assertTrue(nums[1][1] < nums[0][1] < nums[2][1])
        self.assertTrue(nums[2][2] < nums[0][2] < nums[1][2])
예제 #3
0
 def test_defaults(self):
     """Run the report with no configuration options."""
     data = self.get_coverage_data(self.LINES_1)
     opts = CoverageConfig()
     report = self.get_summary_text(data, opts)
     self.assertNotIn('Missing', report)
     self.assertNotIn('Branch', report)
예제 #4
0
 def test_print_missing(self):
     """Run the report printing the missing lines."""
     opts = CoverageConfig()
     opts.from_args(show_missing=True)
     report = self.get_summary_text(opts)
     self.assertIn('Missing', report)
     self.assertNotIn('Branch', report)
예제 #5
0
 def test_sort_report_by_missing(self):
     # Sort the text report by the Missing column.
     opts = CoverageConfig()
     opts.from_args(sort='Miss')
     report = self.get_summary_text(opts)
     self.assert_ordering(report, "test_backward.py", "test_api.py",
                          "test_coverage.py")
예제 #6
0
    def report(self, morfs, outfile=None, config=None):
        conf = CoverageConfig()
        conf.include = ["/pluto/pycloud/*"]
        conf.omit = ["*.txt", "*.xml", '*.tmpl']
        self.find_code_units(None, conf)

        out = open(".coverage.el", "w")

        out.write("(let ((results (make-hash-table :test 'equal)))\n")
        for cu in self.code_units:
            f = cu.filename
            try:
                (fn, executable, missing, mf) = self.coverage.analysis(cu)
            except misc.NoSource:
                continue
            code_linenumbers = executable
            uncovered_code = missing
            covered_linenumbers = sorted(set(executable) - set(missing))
            out.write(
                " (puthash \"%s\" '((%s) (%s) (%s)) results)\n"
                % (f,
                   " ".join([str(ln) for ln in sorted(code_linenumbers)]),
                   " ".join([str(ln) for ln in sorted(covered_linenumbers)]),
                   " ".join([str(ln) for ln in sorted(uncovered_code)])))
        out.write(" results)\n")
        out.close()
예제 #7
0
 def test_sort_report_by_cover(self):
     # Sort the text report by the Cover column.
     data = self.get_coverage_data(self.LINES_1)
     opts = CoverageConfig()
     opts.from_args(sort='Cover')
     report = self.get_summary_text(data, opts)
     self.assert_ordering(report, "test_coverage.py", "test_api.py", "test_backward.py")
예제 #8
0
    def __init__(self, report_file, ignore_errors=False):
        coverage = Coverage(report_file)
        coverage.use_cache(True)
        coverage.load()
        self.config = CoverageConfig()

        super(BasicReporter, self).__init__(coverage, ignore_errors)
예제 #9
0
def test_subtract_omit():
    cfg = CoverageConfig()
    covdefaults.CovDefaults(subtract_omit='*/.tox/*').configure(cfg)
    assert cfg.get_option('run:omit') == [
        '*/__main__.py',
        '*/setup.py',
        '*/venv*/*',
    ]
예제 #10
0
 def model_object(self):
     """Return a Mock suitable for use in CoverageScript."""
     mk = mock.Mock()
     # We'll invoke .coverage as the constructor, and then keep using the
     # same object as the resulting coverage object.
     mk.coverage.return_value = mk
     mk.config = CoverageConfig()
     return mk
예제 #11
0
def test_extends_existing_omit():
    cfg = CoverageConfig()
    cfg.set_option('run:omit', ['pre_commit/resources/*'])
    configure(cfg)
    assert cfg.get_option('run:omit') == [
        '*/.tox/*',
        '*/__main__.py',
        '*/setup.py',
        '*/venv*/*',
        'pre_commit/resources/*',
    ]
예제 #12
0
 def __init__(self,
              report_result,
              html_result=0,
              xml_result=0,
              json_report=0,
              lcov_result=0):
     self.config = CoverageConfig()
     self.report_result = report_result
     self.html_result = html_result
     self.xml_result = xml_result
     self.json_result = json_report
     self.lcov_result = lcov_result
예제 #13
0
    def model_object(self):
        """Return a Mock suitable for use in CoverageScript."""
        mk = mock.Mock()
        # We'll invoke .Coverage as the constructor, and then keep using the
        # same object as the resulting coverage object.
        mk.Coverage.return_value = mk

        # The mock needs to get options, but shouldn't need to set them.
        config = CoverageConfig()
        mk.get_option = config.get_option

        return mk
예제 #14
0
    def model_object(self):
        """Return a Mock suitable for use in CoverageScript."""
        mk = mock.Mock()

        cov = mk.Coverage.return_value

        # The mock needs options.
        mk.config = CoverageConfig()
        cov.get_option = mk.config.get_option
        cov.set_option = mk.config.set_option

        # Get the type right for the result of reporting.
        cov.report.return_value = 50.0
        cov.html_report.return_value = 50.0
        cov.xml_report.return_value = 50.0

        return mk
예제 #15
0
 def report(self, stream):
     """
     Output code coverage report.
     """
     import coverage
     from coverage.config import CoverageConfig
     coverage.stop()
     modules = [
         module for name, module in sys.modules.items()
         if self.wantModuleCoverage(name, module)
     ]
     html_reporter = coverage.html.HtmlReporter(coverage._the_coverage)
     config = CoverageConfig()
     config.html_dir = self.coverHtmlDir
     if self.coverHtmlDir:
         if not os.path.exists(self.coverHtmlDir):
             os.makedirs(self.coverHtmlDir)
         html_reporter.report(modules, config)
예제 #16
0
    def model_object(self):
        """Return a Mock suitable for use in CoverageScript."""
        mk = mock.Mock()
        # We'll invoke .Coverage as the constructor, and then keep using the
        # same object as the resulting coverage object.
        mk.Coverage.return_value = mk

        # The mock needs options.
        config = CoverageConfig()
        mk.get_option = config.get_option
        mk.set_option = config.set_option

        # Get the type right for the result of reporting.
        mk.report.return_value = 50.0
        mk.html_report.return_value = 50.0
        mk.xml_report.return_value = 50.0

        return mk
예제 #17
0
    def __init__(self,
                 data_file=None,
                 data_suffix=None,
                 cover_pylib=None,
                 auto_data=False,
                 timid=None,
                 branch=None,
                 config_file=True,
                 source=None,
                 omit=None,
                 include=None,
                 debug=None,
                 debug_file=None):
        """
        `data_file` is the base name of the data file to use, defaulting to
        ".coverage".  `data_suffix` is appended (with a dot) to `data_file` to
        create the final file name.  If `data_suffix` is simply True, then a
        suffix is created with the machine and process identity included.
        
        `cover_pylib` is a boolean determining whether Python code installed
        with the Python interpreter is measured.  This includes the Python
        standard library and any packages installed with the interpreter.
        
        If `auto_data` is true, then any existing data file will be read when
        coverage measurement starts, and data will be saved automatically when
        measurement stops.
        
        If `timid` is true, then a slower and simpler trace function will be
        used.  This is important for some environments where manipulation of
        tracing functions breaks the faster trace function.
        
        If `branch` is true, then branch coverage will be measured in addition
        to the usual statement coverage.
        
        `config_file` determines what config file to read.  If it is a string,
        it is the name of the config file to read.  If it is True, then a
        standard file is read (".coveragerc").  If it is False, then no file is
        read.
        
        `source` is a list of file paths or package names.  Only code located
        in the trees indicated by the file paths or package names will be
        measured.
        
        `include` and `omit` are lists of filename patterns. Files that match
        `include` will be measured, files that match `omit` will not.  Each
        will also accept a single string argument.
        
        `debug` is a list of strings indicating what debugging information is
        desired. `debug_file` is the file to write debug messages to,
        defaulting to stderr.
        
        """
        from coverage import __version__
        self._warnings = []
        self.config = CoverageConfig()
        if config_file:
            if config_file is True:
                config_file = '.coveragerc'
            try:
                self.config.from_file(config_file)
            except ValueError:
                _, err, _ = sys.exc_info()
                raise CoverageException("Couldn't read config file %s: %s" %
                                        (config_file, err))

        self.config.from_environment('COVERAGE_OPTIONS')
        env_data_file = os.environ.get('COVERAGE_FILE')
        if env_data_file:
            self.config.data_file = env_data_file
        self.config.from_args(data_file=data_file,
                              cover_pylib=cover_pylib,
                              timid=timid,
                              branch=branch,
                              parallel=bool_or_none(data_suffix),
                              source=source,
                              omit=omit,
                              include=include,
                              debug=debug)
        self.debug = DebugControl(self.config.debug, debug_file or sys.stderr)
        self.auto_data = auto_data
        self._exclude_re = {}
        self._exclude_regex_stale()
        self.file_locator = FileLocator()
        self.source = []
        self.source_pkgs = []
        for src in self.config.source or []:
            if os.path.exists(src):
                self.source.append(self.file_locator.canonical_filename(src))
            else:
                self.source_pkgs.append(src)

        self.omit = prep_patterns(self.config.omit)
        self.include = prep_patterns(self.config.include)
        self.collector = Collector(self._should_trace,
                                   timid=self.config.timid,
                                   branch=self.config.branch,
                                   warn=self._warn)
        if data_suffix or self.config.parallel:
            if not isinstance(data_suffix, string_class):
                data_suffix = True
        else:
            data_suffix = None
        self.data_suffix = None
        self.run_suffix = data_suffix
        self.data = CoverageData(basename=self.config.data_file,
                                 collector='coverage v%s' % __version__,
                                 debug=self.debug)
        self.pylib_dirs = []
        if not self.config.cover_pylib:
            for m in (atexit, os, random, socket, _structseq):
                if m is not None and hasattr(m, '__file__'):
                    m_dir = self._canonical_dir(m)
                    if m_dir not in self.pylib_dirs:
                        self.pylib_dirs.append(m_dir)

        self.cover_dir = self._canonical_dir(__file__)
        self.source_match = None
        self.pylib_match = self.cover_match = None
        self.include_match = self.omit_match = None
        Numbers.set_precision(self.config.precision)
        self._warn_no_data = True
        self._warn_unimported_source = True
        self._started = False
        self._measured = False
        atexit.register(self._atexit)
예제 #18
0
def format():
    def should_format_file(path):
        return path.endswith(".py")

    def should_format_doc_file(path):
        return path.endswith((".rst", ".md"))

    changed = tools.modified_files()

    format_all = os.environ.get("FORMAT_ALL", "").lower() == "true"
    if "requirements/tools.txt" in changed:
        # We've changed the tools, which includes a lot of our formatting
        # logic, so we need to rerun formatters.
        format_all = True

    files = tools.all_files() if format_all else changed

    doc_files_to_format = [
        f for f in sorted(files) if should_format_doc_file(f)
    ]
    pip_tool("blacken-docs", *doc_files_to_format)

    files_to_format = [f for f in sorted(files) if should_format_file(f)]

    if not files_to_format:
        return

    # .coveragerc lists several regex patterns to treat as nocover pragmas, and
    # we want to find (and delete) cases where # pragma: no cover is redundant.
    config = CoverageConfig()
    config.from_file(os.path.join(hp.BASE_DIR, ".coveragerc"), our_file=True)
    pattern = "|".join(l for l in config.exclude_list if "pragma" not in l)
    unused_pragma_pattern = re.compile(f"({pattern}).*# pragma: no cover")

    for f in files_to_format:
        lines = []
        with open(f, encoding="utf-8") as o:
            shebang = None
            first = True
            header_done = False
            for l in o.readlines():
                if first:
                    first = False
                    if l[:2] == "#!":
                        shebang = l
                        continue
                if "END HEADER" in l and not header_done:
                    lines = []
                    header_done = True
                elif unused_pragma_pattern.search(l) is not None:
                    lines.append(l.replace("# pragma: no cover", ""))
                else:
                    lines.append(l)
        source = "".join(lines).strip()
        with open(f, "w", encoding="utf-8") as o:
            if shebang is not None:
                o.write(shebang)
                o.write("\n")
            o.write(HEADER)
            if source:
                o.write("\n\n")
                o.write(source)
            o.write("\n")

    pip_tool(
        "autoflake",
        "--recursive",
        "--in-place",
        "--exclude=compat.py",
        "--remove-all-unused-imports",
        "--remove-duplicate-keys",
        "--remove-unused-variables",
        *files_to_format,
    )
    pip_tool("pyupgrade", "--keep-percent-format", "--py36-plus",
             *files_to_format)
    pip_tool("isort", *files_to_format)
    pip_tool("black", "--target-version=py36", *files_to_format)
예제 #19
0
    def __init__(
        self,
        data_file=None,
        data_suffix=None,
        cover_pylib=None,
        auto_data=False,
        timid=None,
        branch=None,
        config_file=True,
        source=None,
        omit=None,
        include=None,
        debug=None,
        concurrency=None,
    ):
        """
        `data_file` is the base name of the data file to use, defaulting to
        ".coverage".  `data_suffix` is appended (with a dot) to `data_file` to
        create the final file name.  If `data_suffix` is simply True, then a
        suffix is created with the machine and process identity included.

        `cover_pylib` is a boolean determining whether Python code installed
        with the Python interpreter is measured.  This includes the Python
        standard library and any packages installed with the interpreter.

        If `auto_data` is true, then any existing data file will be read when
        coverage measurement starts, and data will be saved automatically when
        measurement stops.

        If `timid` is true, then a slower and simpler trace function will be
        used.  This is important for some environments where manipulation of
        tracing functions breaks the faster trace function.

        If `branch` is true, then branch coverage will be measured in addition
        to the usual statement coverage.

        `config_file` determines what configuration file to read:

            * If it is ".coveragerc", it is interpreted as if it were True,
              for backward compatibility.

            * If it is a string, it is the name of the file to read.  If the
              file can't be read, it is an error.

            * If it is True, then a few standard files names are tried
              (".coveragerc", "setup.cfg").  It is not an error for these files
              to not be found.

            * If it is False, then no configuration file is read.

        `source` is a list of file paths or package names.  Only code located
        in the trees indicated by the file paths or package names will be
        measured.

        `include` and `omit` are lists of file name patterns. Files that match
        `include` will be measured, files that match `omit` will not.  Each
        will also accept a single string argument.

        `debug` is a list of strings indicating what debugging information is
        desired.

        `concurrency` is a string indicating the concurrency library being used
        in the measured code.  Without this, coverage.py will get incorrect
        results.  Valid strings are "greenlet", "eventlet", "gevent", or
        "thread" (the default).

        .. versionadded:: 4.0
            The `concurrency` parameter.

        """
        # Build our configuration from a number of sources:
        # 1: defaults:
        self.config = CoverageConfig()

        # 2: from the rcfile, .coveragerc or setup.cfg file:
        if config_file:
            did_read_rc = False
            # Some API users were specifying ".coveragerc" to mean the same as
            # True, so make it so.
            if config_file == ".coveragerc":
                config_file = True
            specified_file = (config_file is not True)
            if not specified_file:
                config_file = ".coveragerc"

            did_read_rc = self.config.from_file(config_file)

            if not did_read_rc:
                if specified_file:
                    raise CoverageException(
                        "Couldn't read '%s' as a config file" % config_file)
                self.config.from_file("setup.cfg", section_prefix="coverage:")

        # 3: from environment variables:
        env_data_file = os.environ.get('COVERAGE_FILE')
        if env_data_file:
            self.config.data_file = env_data_file
        debugs = os.environ.get('COVERAGE_DEBUG')
        if debugs:
            self.config.debug.extend(debugs.split(","))

        # 4: from constructor arguments:
        self.config.from_args(
            data_file=data_file,
            cover_pylib=cover_pylib,
            timid=timid,
            branch=branch,
            parallel=bool_or_none(data_suffix),
            source=source,
            omit=omit,
            include=include,
            debug=debug,
            concurrency=concurrency,
        )

        self._debug_file = None
        self._auto_data = auto_data
        self._data_suffix = data_suffix

        # The matchers for _should_trace.
        self.source_match = None
        self.source_pkgs_match = None
        self.pylib_match = self.cover_match = None
        self.include_match = self.omit_match = None

        # Is it ok for no data to be collected?
        self._warn_no_data = True
        self._warn_unimported_source = True

        # A record of all the warnings that have been issued.
        self._warnings = []

        # Other instance attributes, set later.
        self.omit = self.include = self.source = None
        self.source_pkgs = None
        self.data = self.data_files = self.collector = None
        self.plugins = None
        self.pylib_dirs = self.cover_dirs = None
        self.data_suffix = self.run_suffix = None
        self._exclude_re = None
        self.debug = None

        # State machine variables:
        # Have we initialized everything?
        self._inited = False
        # Have we started collecting and not stopped it?
        self._started = False
        # Have we measured some data and not harvested it?
        self._measured = False
예제 #20
0
    def __init__(self,
                 data_file=None,
                 data_suffix=None,
                 cover_pylib=None,
                 auto_data=False,
                 timid=None,
                 branch=None,
                 config_file=True,
                 source=None,
                 omit=None,
                 include=None):
        """
        `data_file` is the base name of the data file to use, defaulting to
        ".coverage".  `data_suffix` is appended (with a dot) to `data_file` to
        create the final file name.  If `data_suffix` is simply True, then a
        suffix is created with the machine and process identity included.

        `cover_pylib` is a boolean determining whether Python code installed
        with the Python interpreter is measured.  This includes the Python
        standard library and any packages installed with the interpreter.

        If `auto_data` is true, then any existing data file will be read when
        coverage measurement starts, and data will be saved automatically when
        measurement stops.

        If `timid` is true, then a slower and simpler trace function will be
        used.  This is important for some environments where manipulation of
        tracing functions breaks the faster trace function.

        If `branch` is true, then branch coverage will be measured in addition
        to the usual statement coverage.

        `config_file` determines what config file to read.  If it is a string,
        it is the name of the config file to read.  If it is True, then a
        standard file is read (".coveragerc").  If it is False, then no file is
        read.

        `source` is a list of file paths or package names.  Only code located
        in the trees indicated by the file paths or package names will be
        measured.

        `include` and `omit` are lists of filename patterns. Files that match
        `include` will be measured, files that match `omit` will not.  Each
        will also accept a single string argument.

        """
        from coverage import __version__

        # A record of all the warnings that have been issued.
        self._warnings = []

        # Build our configuration from a number of sources:
        # 1: defaults:
        self.config = CoverageConfig()

        # 2: from the coveragerc file:
        if config_file:
            if config_file is True:
                config_file = ".coveragerc"
            try:
                self.config.from_file(config_file)
            except ValueError:
                _, err, _ = sys.exc_info()
                raise CoverageException("Couldn't read config file %s: %s" %
                                        (config_file, err))

        # 3: from environment variables:
        self.config.from_environment('COVERAGE_OPTIONS')
        env_data_file = os.environ.get('COVERAGE_FILE')
        if env_data_file:
            self.config.data_file = env_data_file

        # 4: from constructor arguments:
        self.config.from_args(data_file=data_file,
                              cover_pylib=cover_pylib,
                              timid=timid,
                              branch=branch,
                              parallel=bool_or_none(data_suffix),
                              source=source,
                              omit=omit,
                              include=include)

        self.auto_data = auto_data

        # _exclude_re is a dict mapping exclusion list names to compiled
        # regexes.
        self._exclude_re = {}
        self._exclude_regex_stale()

        self.file_locator = FileLocator()

        # The source argument can be directories or package names.
        self.source = []
        self.source_pkgs = []
        for src in self.config.source or []:
            if os.path.exists(src):
                self.source.append(self.file_locator.canonical_filename(src))
            else:
                self.source_pkgs.append(src)

        self.omit = prep_patterns(self.config.omit)
        self.include = prep_patterns(self.config.include)

        self.collector = Collector(self._should_trace,
                                   timid=self.config.timid,
                                   branch=self.config.branch,
                                   warn=self._warn)

        # Suffixes are a bit tricky.  We want to use the data suffix only when
        # collecting data, not when combining data.  So we save it as
        # `self.run_suffix` now, and promote it to `self.data_suffix` if we
        # find that we are collecting data later.
        if data_suffix or self.config.parallel:
            if not isinstance(data_suffix, string_class):
                # if data_suffix=True, use .machinename.pid.random
                data_suffix = True
        else:
            data_suffix = None
        self.data_suffix = None
        self.run_suffix = data_suffix

        # Create the data file.  We do this at construction time so that the
        # data file will be written into the directory where the process
        # started rather than wherever the process eventually chdir'd to.
        self.data = CoverageData(basename=self.config.data_file,
                                 collector="coverage v%s" % __version__)

        # The dirs for files considered "installed with the interpreter".
        self.pylib_dirs = []
        if not self.config.cover_pylib:
            # Look at where some standard modules are located. That's the
            # indication for "installed with the interpreter". In some
            # environments (virtualenv, for example), these modules may be
            # spread across a few locations. Look at all the candidate modules
            # we've imported, and take all the different ones.
            for m in (atexit, os, random, socket):
                if hasattr(m, "__file__"):
                    m_dir = self._canonical_dir(m)
                    if m_dir not in self.pylib_dirs:
                        self.pylib_dirs.append(m_dir)

        # To avoid tracing the coverage code itself, we skip anything located
        # where we are.
        self.cover_dir = self._canonical_dir(__file__)

        # The matchers for _should_trace, created when tracing starts.
        self.source_match = None
        self.pylib_match = self.cover_match = None
        self.include_match = self.omit_match = None

        # Only _harvest_data once per measurement cycle.
        self._harvested = False

        # Set the reporting precision.
        Numbers.set_precision(self.config.precision)

        # Is it ok for no data to be collected?
        self._warn_no_data = True
        self._started = False

        atexit.register(self._atexit)
예제 #21
0
def test_coverage_init():
    cfg = CoverageConfig()
    plugin_manager = Plugins.load_plugins(['covdefaults'], cfg)
    assert plugin_manager.get('covdefaults.CovDefaults')
예제 #22
0
def configured():
    cfg = CoverageConfig()
    configure(cfg)
    return cfg
예제 #23
0
def test_extends_existing_exclude_lines():
    cfg = CoverageConfig()
    cfg.set_option('report:exclude_lines', ['^if MYPY:$'])
    configure(cfg)
    assert '^if MYPY:$' in cfg.get_option('report:exclude_lines')
예제 #24
0
def format():
    def should_format_file(path):
        return path.endswith(".py")

    def should_format_doc_file(path):
        return path.endswith((".rst", ".md"))

    changed = tools.modified_files()

    format_all = os.environ.get("FORMAT_ALL", "").lower() == "true"
    if "requirements/tools.txt" in changed:
        # We've changed the tools, which includes a lot of our formatting
        # logic, so we need to rerun formatters.
        format_all = True

    files = tools.all_files() if format_all else changed

    doc_files_to_format = [f for f in sorted(files) if should_format_doc_file(f)]
    pip_tool("blacken-docs", *doc_files_to_format)

    files_to_format = [f for f in sorted(files) if should_format_file(f)]

    if not files_to_format:
        return

    # .coveragerc lists several regex patterns to treat as nocover pragmas, and
    # we want to find (and delete) cases where # pragma: no cover is redundant.
    def warn(msg):
        raise Exception(msg)

    config = CoverageConfig()
    config.from_file(os.path.join(hp.BASE_DIR, ".coveragerc"), warn=warn, our_file=True)
    pattern = "|".join(l for l in config.exclude_list if "pragma" not in l)
    unused_pragma_pattern = re.compile(f"(({pattern}).*)  # pragma: no (branch|cover)")

    for f in files_to_format:
        lines = []
        with open(f, encoding="utf-8") as o:
            shebang = None
            first = True
            header_done = False
            for l in o.readlines():
                if first:
                    first = False
                    if l[:2] == "#!":
                        shebang = l
                        continue
                if "END HEADER" in l and not header_done:
                    lines = []
                    header_done = True
                else:
                    lines.append(unused_pragma_pattern.sub(r"\1", l))
        source = "".join(lines).strip()
        with open(f, "w", encoding="utf-8") as o:
            if shebang is not None:
                o.write(shebang)
                o.write("\n")
            o.write(HEADER)
            if source:
                o.write("\n\n")
                o.write(source)
            o.write("\n")

    codespell("--write-changes", *files_to_format, *doc_files_to_format)
    pip_tool("shed", *files_to_format, *doc_files_to_format)
예제 #25
0
    def __init__(self, report_file, ignore_errors=False):
        coverage = Coverage(report_file)
        coverage.load()

        self.config = CoverageConfig()
        self.coverage = coverage
예제 #26
0
    def __init__(self,
                 data_file=None,
                 data_suffix=None,
                 cover_pylib=None,
                 auto_data=False,
                 timid=None,
                 branch=None,
                 config_file=True,
                 source=None,
                 omit=None,
                 include=None):
        """
        `data_file` is the base name of the data file to use, defaulting to
        ".coverage".  `data_suffix` is appended (with a dot) to `data_file` to
        create the final file name.  If `data_suffix` is simply True, then a
        suffix is created with the machine and process identity included.

        `cover_pylib` is a boolean determining whether Python code installed
        with the Python interpreter is measured.  This includes the Python
        standard library and any packages installed with the interpreter.

        If `auto_data` is true, then any existing data file will be read when
        coverage measurement starts, and data will be saved automatically when
        measurement stops.

        If `timid` is true, then a slower and simpler trace function will be
        used.  This is important for some environments where manipulation of
        tracing functions breaks the faster trace function.

        If `branch` is true, then branch coverage will be measured in addition
        to the usual statement coverage.

        `config_file` determines what config file to read.  If it is a string,
        it is the name of the config file to read.  If it is True, then a
        standard file is read (".coveragerc").  If it is False, then no file is
        read.

        `source` is a list of file paths or package names.  Only code located
        in the trees indicated by the file paths or package names will be
        measured.

        `include` and `omit` are lists of filename patterns. Files that match
        `include` will be measured, files that match `omit` will not.

        """
        from coverage import __version__

        # Build our configuration from a number of sources:
        # 1: defaults:
        self.config = CoverageConfig()

        # 2: from the coveragerc file:
        if config_file:
            if config_file is True:
                config_file = ".coveragerc"
            self.config.from_file(config_file)

        # 3: from environment variables:
        self.config.from_environment('COVERAGE_OPTIONS')
        env_data_file = os.environ.get('COVERAGE_FILE')
        if env_data_file:
            self.config.data_file = env_data_file

        # 4: from constructor arguments:
        self.config.from_args(data_file=data_file,
                              cover_pylib=cover_pylib,
                              timid=timid,
                              branch=branch,
                              parallel=bool_or_none(data_suffix),
                              source=source,
                              omit=omit,
                              include=include)

        self.auto_data = auto_data
        self.atexit_registered = False

        self.exclude_re = ""
        self._compile_exclude()

        self.file_locator = FileLocator()

        # The source argument can be directories or package names.
        self.source = []
        self.source_pkgs = []
        for src in self.config.source or []:
            if os.path.exists(src):
                self.source.append(self.file_locator.canonical_filename(src))
            else:
                self.source_pkgs.append(src)

        self.omit = self._abs_files(self.config.omit)
        self.include = self._abs_files(self.config.include)

        self.collector = Collector(self._should_trace,
                                   timid=self.config.timid,
                                   branch=self.config.branch)

        # Suffixes are a bit tricky.  We want to use the data suffix only when
        # collecting data, not when combining data.  So we save it as
        # `self.run_suffix` now, and promote it to `self.data_suffix` if we
        # find that we are collecting data later.
        if data_suffix or self.config.parallel:
            if not isinstance(data_suffix, string_class):
                # if data_suffix=True, use .machinename.pid.random
                data_suffix = True
        else:
            data_suffix = None
        self.data_suffix = None
        self.run_suffix = data_suffix

        # Create the data file.  We do this at construction time so that the
        # data file will be written into the directory where the process
        # started rather than wherever the process eventually chdir'd to.
        self.data = CoverageData(basename=self.config.data_file,
                                 collector="coverage v%s" % __version__)

        # The dirs for files considered "installed with the interpreter".
        self.pylib_dirs = []
        if not self.config.cover_pylib:
            # Look at where the "os" module is located.  That's the indication
            # for "installed with the interpreter".
            os_dir = self.canonical_dir(os.__file__)
            self.pylib_dirs.append(os_dir)

            # In a virtualenv, there're actually two lib directories. Find the
            # other one.  This is kind of ad-hoc, but it works.
            random_dir = self.canonical_dir(random.__file__)
            if random_dir != os_dir:
                self.pylib_dirs.append(random_dir)

        # To avoid tracing the coverage code itself, we skip anything located
        # where we are.
        self.cover_dir = self.canonical_dir(__file__)

        # The matchers for _should_trace, created when tracing starts.
        self.source_match = None
        self.pylib_match = self.cover_match = None
        self.include_match = self.omit_match = None
예제 #27
0
def test_configure_keeps_existing_fail_under():
    cfg = CoverageConfig()
    cfg.set_option('report:fail_under', 42)
    configure(cfg)
    assert cfg.get_option('report:fail_under') == 42
예제 #28
0
 def __init__(self, report_result, html_result, xml_result, json_report):
     self.config = CoverageConfig()
     self.report_result = report_result
     self.html_result = html_result
     self.xml_result = xml_result
     self.json_result = json_report
예제 #29
0
    def __init__(self,
                 data_file=None,
                 data_suffix=None,
                 cover_pylib=None,
                 auto_data=False,
                 timid=None,
                 branch=None,
                 config_file=True,
                 source=None,
                 omit=None,
                 include=None,
                 debug=None,
                 debug_file=None):
        from coverage import __version__
        self._warnings = []
        self.config = CoverageConfig()
        if config_file:
            if config_file is True:
                config_file = '.coveragerc'
            try:
                self.config.from_file(config_file)
            except ValueError:
                _, err, _ = sys.exc_info()
                raise CoverageException("Couldn't read config file %s: %s" %
                                        (config_file, err))

        self.config.from_environment('COVERAGE_OPTIONS')
        env_data_file = os.environ.get('COVERAGE_FILE')
        if env_data_file:
            self.config.data_file = env_data_file
        self.config.from_args(data_file=data_file,
                              cover_pylib=cover_pylib,
                              timid=timid,
                              branch=branch,
                              parallel=bool_or_none(data_suffix),
                              source=source,
                              omit=omit,
                              include=include,
                              debug=debug)
        self.debug = DebugControl(self.config.debug, debug_file or sys.stderr)
        self.auto_data = auto_data
        self._exclude_re = {}
        self._exclude_regex_stale()
        self.file_locator = FileLocator()
        self.source = []
        self.source_pkgs = []
        for src in self.config.source or []:
            if os.path.exists(src):
                self.source.append(self.file_locator.canonical_filename(src))
            else:
                self.source_pkgs.append(src)

        self.omit = prep_patterns(self.config.omit)
        self.include = prep_patterns(self.config.include)
        self.collector = Collector(self._should_trace,
                                   timid=self.config.timid,
                                   branch=self.config.branch,
                                   warn=self._warn)
        if data_suffix or self.config.parallel:
            if not isinstance(data_suffix, string_class):
                data_suffix = True
        else:
            data_suffix = None
        self.data_suffix = None
        self.run_suffix = data_suffix
        self.data = CoverageData(basename=self.config.data_file,
                                 collector='coverage v%s' % __version__,
                                 debug=self.debug)
        self.pylib_dirs = []
        if not self.config.cover_pylib:
            for m in (atexit, os, random, socket, _structseq):
                if m is not None and hasattr(m, '__file__'):
                    m_dir = self._canonical_dir(m)
                    if m_dir not in self.pylib_dirs:
                        self.pylib_dirs.append(m_dir)

        self.cover_dir = self._canonical_dir(__file__)
        self.source_match = None
        self.pylib_match = self.cover_match = None
        self.include_match = self.omit_match = None
        Numbers.set_precision(self.config.precision)
        self._warn_no_data = True
        self._warn_unimported_source = True
        self._started = False
        self._measured = False
        atexit.register(self._atexit)