Python coverage.Coverage() Examples

The following are 30 code examples of coverage.Coverage(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module coverage , or try the search function .
Example #1
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 7 votes vote down vote up
def test_tabbed(self):
        self.output_dir("out/tabbed")

        with change_dir("src"):
            # pylint: disable=import-error
            cov = coverage.Coverage()
            cov.start()
            import tabbed           # pragma: nested
            cov.stop()              # pragma: nested
            cov.html_report(tabbed, directory="../out/tabbed")

        # Editors like to change things, make sure our source file still has tabs.
        contains("src/tabbed.py", "\tif x:\t\t\t\t\t# look nice")

        contains(
            "out/tabbed/tabbed_py.html",
            '>        <span class="key">if</span> '
            '<span class="nam">x</span><span class="op">:</span>'
            '                                   '
            '<span class="com"># look nice</span>'
        )

        doesnt_contain("out/tabbed/tabbed_py.html", "\t") 
Example #2
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_include_can_measure_stdlib(self):
        self.make_file("mymain.py", """\
            import colorsys, random
            a = 1
            r, g, b = [random.random() for _ in range(3)]
            hls = colorsys.rgb_to_hls(r, g, b)
            """)

        # Measure without the stdlib, but include colorsys.
        cov1 = coverage.Coverage(cover_pylib=False, include=["*/colorsys.py"])
        self.start_import_stop(cov1, "mymain")

        # some statements were marked executed in colorsys.py
        _, statements, missing, _ = cov1.analysis("colorsys.py")
        self.assertNotEqual(statements, missing)
        # but none were in random.py
        _, statements, missing, _ = cov1.analysis("random.py")
        self.assertEqual(statements, missing) 
Example #3
Source File: runner.py    From recipes-py with Apache License 2.0 6 votes vote down vote up
def _cover_all_imports(main_repo):
  # If our process is supposed to collect coverage for all recipe module
  # imports, do that after we recieve the first Description. This way we can
  # reply to the main process with an Outcome. Otherwise the main process
  # could be blocked on writing a Description while we're trying to write an
  # Outcome.
  if not main_repo.modules:
    # Prevents a coverage warning when there are no modules to collect coverage
    # from.
    return coverage.CoverageData()

  mod_dir_base = os.path.join(main_repo.recipes_root_path, 'recipe_modules')
  cov = coverage.Coverage(config_file=False, include=[
    os.path.join(mod_dir_base, '*', '*.py')
  ])
  cov.start()
  for module in main_repo.modules.itervalues():
    # Allow exceptions to raise here; they'll be reported as a 'global'
    # failure.
    module.do_import()
  cov.stop()
  return cov.get_data()

# administrative stuff (main, pipe handling, etc.) 
Example #4
Source File: test_config.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_parse_errors(self):
        # Im-parsable values raise CoverageException, with details.
        bad_configs_and_msgs = [
            ("[run]\ntimid = maybe?\n", r"maybe[?]"),
            ("timid = 1\n", r"timid = 1"),
            ("[run\n", r"\[run"),
            ("[report]\nexclude_lines = foo(\n",
                r"Invalid \[report\].exclude_lines value 'foo\(': "
                r"(unbalanced parenthesis|missing \))"),
            ("[report]\npartial_branches = foo[\n",
                r"Invalid \[report\].partial_branches value 'foo\[': "
                r"(unexpected end of regular expression|unterminated character set)"),
            ("[report]\npartial_branches_always = foo***\n",
                r"Invalid \[report\].partial_branches_always value "
                r"'foo\*\*\*': "
                r"multiple repeat"),
        ]

        for bad_config, msg in bad_configs_and_msgs:
            print("Trying %r" % bad_config)
            self.make_file(".coveragerc", bad_config)
            with self.assertRaisesRegex(CoverageException, msg):
                coverage.Coverage() 
Example #5
Source File: __main__.py    From coverage-badge with MIT License 6 votes vote down vote up
def get_total():
    """
    Return the rounded total as properly rounded string.
    """
    cov = coverage.Coverage()
    cov.load()
    total = cov.report(file=Devnull())

    class Precision(coverage.results.Numbers):
        """
        A class for using the percentage rounding of the main coverage package,
        with any percentage.

        To get the string format of the percentage, use the ``pc_covered_str``
        property.

        """
        def __init__(self, percent):
            self.percent = percent

        @property
        def pc_covered(self):
            return self.percent

    return Precision(total).pc_covered_str 
Example #6
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def pretend_to_be_nose_with_cover(self, erase):
        """This is what the nose --with-cover plugin does."""
        cov = coverage.Coverage()

        self.make_file("no_biggie.py", """\
            a = 1
            b = 2
            if b == 1:
                c = 4
            """)

        if erase:
            cov.combine()
            cov.erase()
        cov.load()
        self.start_import_stop(cov, "no_biggie")
        cov.combine()
        cov.save()
        cov.report(["no_biggie.py"], show_missing=True)
        self.assertEqual(self.stdout(), textwrap.dedent("""\
            Name           Stmts   Miss  Cover   Missing
            --------------------------------------------
            no_biggie.py       4      1    75%   4
            """)) 
Example #7
Source File: test_config.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_environment_vars_in_config(self):
        # Config files can have $envvars in them.
        self.make_file(".coveragerc", """\
            [run]
            data_file = $DATA_FILE.fooey
            branch = $OKAY
            [report]
            exclude_lines =
                the_$$one
                another${THING}
                x${THING}y
                x${NOTHING}y
                huh$${X}what
            """)
        self.set_environ("DATA_FILE", "hello-world")
        self.set_environ("THING", "ZZZ")
        self.set_environ("OKAY", "yes")
        cov = coverage.Coverage()
        self.assertEqual(cov.config.data_file, "hello-world.fooey")
        self.assertEqual(cov.config.branch, True)
        self.assertEqual(
            cov.config.exclude_list,
            ["the_$one", "anotherZZZ", "xZZZy", "xy", "huh${X}what"]
        ) 
Example #8
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_dotpy_not_python_ignored(self):
        self.make_file("main.py", "import innocuous")
        self.make_file("innocuous.py", "a = 2")
        cov = coverage.Coverage()
        self.start_import_stop(cov, "main")
        self.make_file("innocuous.py", "<h1>This isn't python!</h1>")
        cov.html_report(ignore_errors=True)
        self.assertEqual(
            len(cov._warnings),
            1,
            "Expected a warning to be thrown when an invalid python file is parsed")
        self.assertIn(
            "Could not parse Python file",
            cov._warnings[0],
            "Warning message should be in 'invalid file' warning"
        )
        self.assertIn(
            "innocuous.py",
            cov._warnings[0],
            "Filename should be in 'invalid file' warning"
        )
        self.assert_exists("htmlcov/index.html")
        # This would be better as a glob, if the HTML layout changes:
        self.assert_doesnt_exist("htmlcov/innocuous.html") 
Example #9
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def coverage_usepkgs(self, **kwargs):
        """Run coverage on usepkgs and return the line summary.

        Arguments are passed to the `coverage.Coverage` constructor.

        """
        cov = coverage.Coverage(**kwargs)
        cov.start()
        import usepkgs  # pragma: nested   # pylint: disable=import-error, unused-variable
        cov.stop()      # pragma: nested
        data = cov.get_data()
        summary = data.line_counts()
        for k, v in list(summary.items()):
            assert k.endswith(".py")
            summary[k[:-3]] = v
        return summary 
Example #10
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_source_and_include_dont_conflict(self):
        # A bad fix made this case fail: https://bitbucket.org/ned/coveragepy/issues/541
        self.make_file("a.py", "import b\na = 1")
        self.make_file("b.py", "b = 1")
        self.make_file(".coveragerc", """\
            [run]
            source = .
            """)

        # Just like: coverage run a.py
        cov = coverage.Coverage()
        self.start_import_stop(cov, "a")
        cov.save()

        # Run the equivalent of: coverage report --include=b.py
        cov = coverage.Coverage(include=["b.py"])
        cov.load()
        # There should be no exception. At one point, report() threw:
        # CoverageException: --include and --source are mutually exclusive
        cov.report()
        self.assertEqual(self.stdout(), textwrap.dedent("""\
            Name    Stmts   Miss  Cover
            ---------------------------
            b.py        1      0   100%
            """)) 
Example #11
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_copying_static_files_from_system_in_dir(self):
        # Make a new place for static files.
        INSTALLED = [
            "jquery/jquery.min.js",
            "jquery-hotkeys/jquery.hotkeys.js",
            "jquery-isonscreen/jquery.isonscreen.js",
            "jquery-tablesorter/jquery.tablesorter.min.js",
        ]
        for fpath in INSTALLED:
            self.make_file(os.path.join("static_here", fpath), "Not real.")
        coverage.html.STATIC_PATH.insert(0, "static_here")

        self.make_file("main.py", "print(17)")
        cov = coverage.Coverage()
        self.start_import_stop(cov, "main")
        cov.html_report()

        for fpath in INSTALLED:
            the_file = os.path.basename(fpath)
            with open(os.path.join("htmlcov", the_file)) as f:
                contents = f.read()
            self.assertEqual(contents, "Not real.") 
Example #12
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_combining_twice(self):
        self.make_good_data_files()
        cov1 = coverage.Coverage()
        cov1.combine()
        cov1.save()
        self.check_code1_code2(cov1)

        cov2 = coverage.Coverage()
        with self.assertRaisesRegex(CoverageException, r"No data to combine"):
            cov2.combine(strict=True)

        cov3 = coverage.Coverage()
        cov3.combine()
        # Now the data is empty!
        _, statements, missing, _ = cov3.analysis("code1.py")
        self.assertEqual(statements, [1])
        self.assertEqual(missing, [1])
        _, statements, missing, _ = cov3.analysis("code2.py")
        self.assertEqual(statements, [1, 2])
        self.assertEqual(missing, [1, 2]) 
Example #13
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_combining_corrupt_data(self):
        # If you combine a corrupt data file, then you will get a warning,
        # and the file will remain.
        self.make_good_data_files()
        self.make_bad_data_file()
        cov = coverage.Coverage()
        warning_regex = (
            r"Couldn't read data from '.*\.coverage\.foo': "
            r"CoverageException: Doesn't seem to be a coverage\.py data file"
        )
        with self.assert_warnings(cov, [warning_regex]):
            cov.combine()

        # We got the results from code1 and code2 properly.
        self.check_code1_code2(cov)

        # The bad file still exists.
        self.assert_exists(".coverage.foo") 
Example #14
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_isolatin1(self):
        self.output_dir("out/isolatin1")

        with change_dir("src"):
            # pylint: disable=import-error
            cov = coverage.Coverage()
            cov.start()
            import isolatin1            # pragma: nested
            cov.stop()                  # pragma: nested
            cov.html_report(isolatin1, directory="../out/isolatin1")

        compare("gold_isolatin1", "out/isolatin1", size_within=10, file_pattern="*.html")
        contains(
            "out/isolatin1/isolatin1_py.html",
            '<span class="str">"3&#215;4 = 12, &#247;2 = 6&#177;0"</span>',
        ) 
Example #15
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_other(self):
        self.output_dir("out/other")

        with change_dir("src"):
            # pylint: disable=import-error
            sys.path.insert(0, "../othersrc")
            cov = coverage.Coverage(include=["./*", "../othersrc/*"])
            cov.start()
            import here         # pragma: nested # pylint: disable=unused-variable
            cov.stop()          # pragma: nested
            cov.html_report(directory="../out/other")

        # Different platforms will name the "other" file differently. Rename it
        for p in glob.glob("out/other/*_other_py.html"):
            os.rename(p, "out/other/blah_blah_other_py.html")

        compare("gold_other", "out/other", size_within=10, file_pattern="*.html")
        contains(
            "out/other/index.html",
            '<a href="here_py.html">here.py</a>',
            'other_py.html">', 'other.py</a>',
        ) 
Example #16
Source File: test_html.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_unicode(self):
        self.output_dir("out/unicode")

        with change_dir("src"):
            # pylint: disable=import-error, redefined-builtin
            cov = coverage.Coverage()
            cov.start()
            import unicode          # pragma: nested
            cov.stop()              # pragma: nested
            cov.html_report(unicode, directory="../out/unicode")

        compare("gold_unicode", "out/unicode", size_within=10, file_pattern="*.html")
        contains(
            "out/unicode/unicode_py.html",
            '<span class="str">"&#654;d&#729;&#477;b&#592;&#633;&#477;&#652;o&#596;"</span>',
        )

        contains_any(
            "out/unicode/unicode_py.html",
            '<span class="str">"db40,dd00: x&#56128;&#56576;"</span>',
            '<span class="str">"db40,dd00: x&#917760;"</span>',
        ) 
Example #17
Source File: test_process.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_warn_preimported(self):
        self.make_file("hello.py", """\
            import goodbye
            import coverage
            cov = coverage.Coverage(include=["good*"], check_preimported=True)
            cov.start()
            print(goodbye.f())
            cov.stop()
            """)
        self.make_file("goodbye.py", """\
            def f():
                return "Goodbye!"
            """)
        goodbye_path = os.path.abspath("goodbye.py")

        out = self.run_command("python hello.py")
        self.assertIn("Goodbye!", out)

        msg = (
            "Coverage.py warning: "
            "Already imported a file that will be measured: {0} "
            "(already-imported)").format(goodbye_path)
        self.assertIn(msg, out) 
Example #18
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_warnings_suppressed(self):
        self.make_file("hello.py", """\
            import sys, os
            print("Hello")
            """)
        self.make_file(".coveragerc", """\
            [run]
            disable_warnings = no-data-collected, module-not-imported
            """)
        cov = coverage.Coverage(source=["sys", "xyzzy", "quux"])
        self.start_import_stop(cov, "hello")
        cov.get_data()

        out = self.stdout()
        self.assertIn("Hello\n", out)

        err = self.stderr()
        self.assertIn(textwrap.dedent("""\
            Coverage.py warning: Module sys has no Python source. (module-not-python)
            """), err)
        self.assertNotIn("module-not-imported", err)
        self.assertNotIn("no-data-collected", err) 
Example #19
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 6 votes vote down vote up
def test_warnings(self):
        self.make_file("hello.py", """\
            import sys, os
            print("Hello")
            """)
        cov = coverage.Coverage(source=["sys", "xyzzy", "quux"])
        self.start_import_stop(cov, "hello")
        cov.get_data()

        out = self.stdout()
        self.assertIn("Hello\n", out)

        err = self.stderr()
        self.assertIn(textwrap.dedent("""\
            Coverage.py warning: Module sys has no Python source. (module-not-python)
            Coverage.py warning: Module xyzzy was never imported. (module-not-imported)
            Coverage.py warning: Module quux was never imported. (module-not-imported)
            Coverage.py warning: No data was collected. (no-data-collected)
            """), err) 
Example #20
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_exclude_list(self):
        cov = coverage.Coverage()
        cov.clear_exclude()
        self.assertEqual(cov.get_exclude_list(), [])
        cov.exclude("foo")
        self.assertEqual(cov.get_exclude_list(), ["foo"])
        cov.exclude("bar")
        self.assertEqual(cov.get_exclude_list(), ["foo", "bar"])
        self.assertEqual(cov._exclude_regex('exclude'), "(?:foo)|(?:bar)")
        cov.clear_exclude()
        self.assertEqual(cov.get_exclude_list(), []) 
Example #21
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_datafile_specified(self):
        # You can specify the data file name.
        self.make_file("datatest2.py", """\
            fooey = 17
            """)

        self.assertFiles(["datatest2.py"])
        cov = coverage.Coverage(data_file="cov.data")
        self.start_import_stop(cov, "datatest2")
        cov.save()
        self.assertFiles(["datatest2.py", "cov.data"]) 
Example #22
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_datafile_and_suffix_specified(self):
        # You can specify the data file name and suffix.
        self.make_file("datatest3.py", """\
            fooey = 17
            """)

        self.assertFiles(["datatest3.py"])
        cov = coverage.Coverage(data_file="cov.data", data_suffix="14")
        self.start_import_stop(cov, "datatest3")
        cov.save()
        self.assertFiles(["datatest3.py", "cov.data.14"]) 
Example #23
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_datafile_default(self):
        # Default data file behavior: it's .coverage
        self.make_file("datatest1.py", """\
            fooey = 17
            """)

        self.assertFiles(["datatest1.py"])
        cov = coverage.Coverage()
        self.start_import_stop(cov, "datatest1")
        cov.save()
        self.assertFiles(["datatest1.py", ".coverage"]) 
Example #24
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_exclude_partial_list(self):
        cov = coverage.Coverage()
        cov.clear_exclude(which='partial')
        self.assertEqual(cov.get_exclude_list(which='partial'), [])
        cov.exclude("foo", which='partial')
        self.assertEqual(cov.get_exclude_list(which='partial'), ["foo"])
        cov.exclude("bar", which='partial')
        self.assertEqual(cov.get_exclude_list(which='partial'), ["foo", "bar"])
        self.assertEqual(
            cov._exclude_regex(which='partial'), "(?:foo)|(?:bar)"
        )
        cov.clear_exclude(which='partial')
        self.assertEqual(cov.get_exclude_list(which='partial'), []) 
Example #25
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_empty_reporting(self):
        # empty summary reports raise exception, just like the xml report
        cov = coverage.Coverage()
        cov.erase()
        self.assertRaises(CoverageException, cov.report) 
Example #26
Source File: test_config.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_debug_from_environment(self):
        self.make_file(".coveragerc", """\
            [run]
            debug = dataio, pids
            """)
        self.set_environ("COVERAGE_DEBUG", "callers, fooey")
        cov = coverage.Coverage()
        self.assertEqual(cov.config.debug, ["dataio", "pids", "callers", "fooey"]) 
Example #27
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_start_save_stop(self):
        self.make_code1_code2()
        cov = coverage.Coverage()
        cov.start()
        import_local_file("code1")                                     # pragma: nested
        cov.save()                                                     # pragma: nested
        import_local_file("code2")                                     # pragma: nested
        cov.stop()                                                     # pragma: nested
        self.check_code1_code2(cov) 
Example #28
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_two_getdata_only_warn_once_nostop(self):
        self.make_code1_code2()
        cov = coverage.Coverage(source=["."], omit=["code1.py"])
        cov.start()
        import_local_file("code1")                                     # pragma: nested
        # We didn't collect any data, so we should get a warning.
        with self.assert_warnings(cov, ["No data was collected"]):     # pragma: nested
            cov.get_data()                                             # pragma: nested
        # But calling get_data a second time with no intervening activity
        # won't make another warning.
        with self.assert_warnings(cov, []):                            # pragma: nested
            cov.get_data()                                             # pragma: nested
        # Then stop it, or the test suite gets out of whack.
        cov.stop()                                                     # pragma: nested 
Example #29
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_start_save_nostop(self):
        self.make_code1_code2()
        cov = coverage.Coverage()
        cov.start()
        import_local_file("code1")                                     # pragma: nested
        cov.save()                                                     # pragma: nested
        import_local_file("code2")                                     # pragma: nested
        self.check_code1_code2(cov)                                    # pragma: nested
        # Then stop it, or the test suite gets out of whack.
        cov.stop()                                                     # pragma: nested 
Example #30
Source File: test_api.py    From coveragepy-bbmirror with Apache License 2.0 5 votes vote down vote up
def test_datafile_from_rcfile(self):
        # You can specify the data file name in the .coveragerc file
        self.make_file("datatest4.py", """\
            fooey = 17
            """)
        self.make_file(".coveragerc", """\
            [run]
            data_file = mydata.dat
            """)

        self.assertFiles(["datatest4.py", ".coveragerc"])
        cov = coverage.Coverage()
        self.start_import_stop(cov, "datatest4")
        cov.save()
        self.assertFiles(["datatest4.py", ".coveragerc", "mydata.dat"])