Beispiel #1
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)
    def test_plugin_init(self):
        self.make_file('coveragerc_test_config', '')

        debug_out = StringIO()
        cov = Coverage(config_file='coveragerc_test_config', debug=['sys'])
        cov._debug_file = debug_out
        cov.set_option('run:plugins', ['coverage_config_reload_plugin'])
        cov.start()
        cov.stop()

        out_lines = [
            line.strip() for line in debug_out.getvalue().splitlines()
        ]
        self.assertIn('plugins.file_tracers: -none-', out_lines)

        expected_end = [
            '-- sys: coverage_config_reload_plugin.ConfigReloadPlugin -----',
            'configreload: True',
            '-- end -------------------------------------------------------',
        ]
        self.assertEqual(expected_end, out_lines[-len(expected_end):])

        if LooseVersion(coverage_version) >= LooseVersion('4.6'):
            self.assertIn(
                'plugins.configurers: coverage_config_reload_plugin.ConfigReloadPlugin',
                out_lines)
    def _check_config(self, filename, own_rc):
        section = 'report' if own_rc else 'coverage:report'

        # Force own rc for pre 4.4.1
        if LooseVersion(coverage_version) < LooseVersion('4.4.1'):
            self.make_file(
                filename, """\
                [report]
                ignore_errors = true
                """)
        else:
            self.make_file(
                filename, """\
                [{}]
                ignore_errors = true
                """.format(section))

        debug_out = StringIO()
        cov = Coverage(config_file=filename, debug=['sys'])
        assert cov.config.get_option('report:ignore_errors') is True
        cov._debug_file = debug_out

        self.make_file(
            filename, """\
            [{}]
            ignore_errors = off
            """.format(section))

        cov.set_option('run:plugins', ['coverage_config_reload_plugin'])
        cov.start()
        cov.stop()

        assert cov.config.get_option('report:ignore_errors') is False
Beispiel #4
0
    def get_coverage(args: list, root_path: str, module_use=False) -> Dict[str, Line]:
        """
        Returns Dict of covered line's Line object.
         :param args: list of module name and target testcase want to get coverage
         :param root_path: target src root want to get coverage
         :return: {
             Line1_hash: {file_path, line_no, line_text},
             Line2_hash: {file_path, line_no, line_text}
         }
        1. cover 한 라인 (file path, line no, line text)
        2. file path 가 root 에 포함되는가.
        2. Line(line text, line no, file path)
        3. res_dict[Line.getHash()] = Line
        4. return res_dict
        """

        regular_path = os.path.abspath(root_path)
        covered = defaultdict(Line)
        # path 에 해당하는 .py file run.
        # report 에 covered line 정보 담겨있음.
        cov = Coverage()
        # args = args[:1] + [root_path] + args[1:]
        runner = PyRunner(args, as_module=module_use)
        runner.prepare()

        cov.start()
        code_ran = True
        try:
            runner.run()
        except NoSource:
            code_ran = False
            raise
        finally:
            cov.stop()
            if code_ran:
                cov.save()

            # testcase.py args 없다고 가정.
            report = get_analysis_to_report(cov, [])
            try:
                for fr, analysis in report:
                    # report : [(file1, [line1, line2, ...]), (), ...]
                    fn = fr.filename
                    if regular_path not in fn:
                        continue

                    if os.path.splitext(fn)[-1] != ".py":
                        continue

                    with open(fn, 'r', encoding="UTF8") as f:
                        lines = f.readlines()
                        if lines:
                            for line_no in analysis.executed:
                                lo = Line(fr.filename, line_no, lines[line_no-1])
                                covered[lo.getHash()] = lo
                        f.close()
            except CoverageException:
                print("There is no Test ran")

            return covered
Beispiel #5
0
    def get_summary_text(self, options):
        """Get text output from the SummaryReporter."""
        self.make_rigged_file("file1.py", 339, 155)
        self.make_rigged_file("file2.py", 13, 3)
        self.make_rigged_file("file3.py", 234, 228)
        self.make_file("doit.py", "import file1, file2, file3")

        cov = Coverage(source=["."], omit=["doit.py"])
        cov.start()
        import doit             # pragma: nested # pylint: disable=import-error, unused-import
        cov.stop()              # pragma: nested
        printer = SummaryReporter(cov, options)
        destination = StringIO()
        printer.report([], destination)
        return destination.getvalue()
def test_write_coverage():

    a = {
        'test1': {
            'a': [1]
        },
        'test2': {
            'a': [2]
        },
    }

    expected = {'lines': {os.path.abspath('a'): [1, 2]}}

    with tempdir() as base:
        path = os.path.join(base, '.coverage')

        cov = Coverage(data_file=path)

        smother = Smother(cov)
        smother.data = a
        smother.write_coverage()

        header_len = 63
        with open(path) as infile:
            infile.seek(header_len)
            result = json.load(infile)

        assert result == expected
Beispiel #7
0
    def get_summary_text(self, *options):
        """Get text output from the SummaryReporter.

        The arguments are tuples: (name, value) for Coverage.set_option.
        """
        self.make_rigged_file("file1.py", 339, 155)
        self.make_rigged_file("file2.py", 13, 3)
        self.make_rigged_file("file10.py", 234, 228)
        self.make_file("doit.py", "import file1, file2, file10")

        cov = Coverage(source=["."], omit=["doit.py"])
        self.start_import_stop(cov, "doit")
        for name, value in options:
            cov.set_option(name, value)
        printer = SummaryReporter(cov)
        destination = io.StringIO()
        printer.report([], destination)
        return destination.getvalue()
 def get_summary_text(self, coverage_data, options):
     """Get text output from the SummaryReporter."""
     cov = Coverage()
     cov.start()
     cov.stop()  # pragma: nested
     cov.data = coverage_data
     printer = SummaryReporter(cov, options)
     destination = StringIO()
     printer.report([], destination)
     return destination.getvalue()
Beispiel #9
0
    def test_plugin_init(self):
        self._reset_env()

        self.make_file(
            '.coveragerc', """\
            [run]
            plugins = coverage_env_plugin

            [coverage_env_plugin]
            markers = True

            [report]
            exclude_lines =
              foobar: no cover
            """)

        cov = Coverage()
        assert cov.config.get_option('report:exclude_lines') == [
            'foobar: no cover'
        ]

        cov.start()
        cov.stop()

        assert cov.config.plugins == ['coverage_env_plugin']
        assert cov.config.plugin_options == {
            'coverage_env_plugin': {
                'markers': 'True'
            }
        }

        assert 'OS_NAME' in coverage_env_plugin.DEFAULT_ENVIRONMENT
        assert 'OS_NAME' in os.environ
Beispiel #10
0
    def test_os_name_without_reload(self):
        self._reset_env()

        self.make_file(
            '.coveragerc', """\
            [run]
            plugins = coverage_env_plugin
            [coverage_env_plugin]
            markers = True
            [report]
            exclude_lines =
              pragma ${OS_NAME}: no cover
            """)

        cov = Coverage(config_file='.coveragerc')

        assert cov.config.get_option('report:exclude_lines') == [
            'pragma : no cover'
        ]
        assert cov.config.exclude_list == ['pragma : no cover']

        assert cov.config.get_option('coverage_env_plugin:markers') == 'True'

        cov.start()
        cov.stop()

        assert 'OS_NAME' in coverage_env_plugin.DEFAULT_ENVIRONMENT

        # It doesnt work; result is the same as the original config
        assert cov.config.get_option('report:exclude_lines') == [
            'pragma : no cover'
        ]
        assert cov.config.exclude_list == ['pragma : no cover']
    def __init__(self, test_labels, options):
        super(Task, self).__init__(test_labels, options)
        self.test_apps = get_apps_under_test(test_labels, options['test_all'])
        self.output_dir = options['output_dir']
        self.with_migrations = options.get('coverage_with_migrations',
                                    getattr(settings,
                                            'COVERAGE_WITH_MIGRATIONS', False))

        self.html_dir = options.get('coverage_html_report_dir') or \
                            getattr(settings,
                                    'COVERAGE_REPORT_HTML_OUTPUT_DIR', '')

        self.branch = options.get('coverage_measure_branch',
                                  getattr(settings,
                                          'COVERAGE_MEASURE_BRANCH', True))

        self.exclude_locations = []
        modnames = options.get('coverage_excludes') or \
                        getattr(settings, 'COVERAGE_EXCLUDES', [])
        for modname in modnames:
            try:
                self.exclude_locations.append(
                        os.path.dirname(
                            import_module(modname).__file__
                        )
                )
            except ImportError:
                pass

        # Extra folders to exclude. Particularly useful to specify things like
        # apps/company/migrations/*
        self.exclude_locations.extend(
                        getattr(settings, 'COVERAGE_EXCLUDES_FOLDERS', []))
        #import ipdb; ipdb.set_trace()

        self.coverage = Coverage(branch=self.branch,
                                 source=self.test_apps,
                                 omit=self.exclude_locations,
                                 config_file=options.get('coverage_rcfile') or
                                                 Task.default_config_path())
Beispiel #12
0
    def test_os_name(self):
        self._reset_env()

        self.make_file(
            '.coveragerc', """\
            [run]
            plugins = coverage_env_plugin, coverage_config_reload_plugin
            [coverage_env_plugin]
            markers = True
            [report]
            exclude_lines =
              pragma ${OS_NAME}: no cover
            """)

        cov = Coverage(config_file='.coveragerc')

        assert cov.config.get_option('report:exclude_lines') == [
            'pragma : no cover'
        ]
        assert cov.config.exclude_list == ['pragma : no cover']

        assert cov.config.get_option('coverage_env_plugin:markers') == 'True'

        cov.start()
        cov.stop()

        assert 'OS_NAME' in coverage_env_plugin.DEFAULT_ENVIRONMENT

        os_name = coverage_env_plugin.DEFAULT_ENVIRONMENT['OS_NAME']
        os_name_pragma = 'pragma {}: no cover'.format(os_name)

        assert cov.config.get_option('report:exclude_lines') == [
            os_name_pragma
        ]
        assert cov.config.exclude_list == [os_name_pragma]
    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)
Beispiel #14
0
    def test_reload_plugin_init(self):
        self._reset_env()

        self.make_file(
            '.coveragerc', """\
            [run]
            plugins = coverage_env_plugin, coverage_config_reload_plugin
            [coverage_env_plugin]
            markers = True
            [report]
            exclude_lines =
              pragma ${OS_NAME}: no cover
            """)

        debug_out = StringIO()
        cov = Coverage(config_file='.coveragerc', debug=['sys'])
        cov._debug_file = debug_out
        cov.set_option(
            'run:plugins',
            ['coverage_env_plugin', 'coverage_config_reload_plugin'])
        cov.start()
        cov.stop()

        assert cov.config.get_option('coverage_env_plugin:markers') == 'True'

        out_lines = [
            line.strip() for line in debug_out.getvalue().splitlines()
        ]
        self.assertIn('plugins.file_tracers: -none-', out_lines)

        if LooseVersion(config_reload_version) >= LooseVersion('0.3.0'):
            expected_end = [
                '-- sys: coverage_config_reload_plugin.ConfigReloadPlugin -----',
                'configreload: True',
                '-- end -------------------------------------------------------',
            ]
            self.assertEqual(expected_end, out_lines[-len(expected_end):])

            if LooseVersion(coverage_version) >= LooseVersion('4.6'):
                self.assertIn(
                    'plugins.configurers: coverage_config_reload_plugin.ConfigReloadPlugin',
                    out_lines)
Beispiel #15
0
 def get_summary_text(self, coverage_data, options):
     """Get text output from the SummaryReporter."""
     cov = Coverage()
     cov.start()
     cov.stop()              # pragma: nested
     cov.data = coverage_data
     printer = SummaryReporter(cov, options)
     destination = StringIO()
     printer.report([], destination)
     return destination.getvalue()
    def test_no_reload_plugin(self):
        debug_out = StringIO()
        cov = Coverage(debug=['sys'])
        cov._debug_file = debug_out
        cov.set_option('run:plugins', [])
        cov.start()
        cov.stop()

        out_lines = [
            line.strip() for line in debug_out.getvalue().splitlines()
        ]
        self.assertIn('plugins.file_tracers: -none-', out_lines)

        expected_end = [
            '-- end -------------------------------------------------------',
        ]
        self.assertEqual(expected_end, out_lines[-len(expected_end):])

        if LooseVersion(coverage_version) >= LooseVersion('4.6'):
            self.assertIn('plugins.configurers: -none-', out_lines)

        assert cov.config.get_option('report:ignore_errors') is False
Beispiel #17
0
    def get_summary_text(self, *options):
        """Get text output from the SummaryReporter.

        The arguments are tuples: (name, value) for Coverage.set_option.
        """
        self.make_rigged_file("file1.py", 339, 155)
        self.make_rigged_file("file2.py", 13, 3)
        self.make_rigged_file("file3.py", 234, 228)
        self.make_file("doit.py", "import file1, file2, file3")

        cov = Coverage(source=["."], omit=["doit.py"])
        cov.start()
        import doit  # pragma: nested # pylint: disable=import-error, unused-import
        cov.stop()  # pragma: nested
        for name, value in options:
            cov.set_option(name, value)
        printer = SummaryReporter(cov)
        destination = StringIO()
        printer.report([], destination)
        return destination.getvalue()
    def get_summary_text(self, options):
        """Get text output from the SummaryReporter."""
        self.make_rigged_file("file1.py", 339, 155)
        self.make_rigged_file("file2.py", 13, 3)
        self.make_rigged_file("file3.py", 234, 228)
        self.make_file("doit.py", "import file1, file2, file3")

        cov = Coverage(source=["."], omit=["doit.py"])
        cov.start()
        import doit  # pragma: nested # pylint: disable=import-error, unused-variable
        cov.stop()  # pragma: nested
        printer = SummaryReporter(cov, options)
        destination = StringIO()
        printer.report([], destination)
        return destination.getvalue()
Beispiel #19
0
    def __init__(self, report_file, ignore_errors=False):
        coverage = Coverage(report_file)
        coverage.load()

        self.config = CoverageConfig()
        self.coverage = coverage
Beispiel #20
0
 def wrapper(*args, **kwargs):
     """Singleton wrapper around a coverage method."""
     global _the_coverage
     if not _the_coverage:
         _the_coverage = Coverage(auto_data=True)
     return getattr(_the_coverage, name)(*args, **kwargs)
class Task(BaseTask):
    option_list = [
           make_option("--coverage-rcfile",
                       dest="coverage_rcfile",
                       default="",
               help="Specify configuration file."),
           make_option("--coverage-html-report",
                       dest="coverage_html_report_dir",
                       default="",
               help="Directory to which HTML coverage report should be"
                    " written. If not specified, no report is generated."),
           make_option("--coverage-no-branch-measure",
                       action="store_false", default=True,
                       dest="coverage_measure_branch",
               help="Don't measure branch coverage."),
           make_option("--coverage-with-migrations",
                       action="store_true", default=False,
                       dest="coverage_with_migrations",
               help="Don't measure migrations coverage."),
           make_option("--coverage-exclude", action="append",
                       default=[], dest="coverage_excludes",
               help="Module name to exclude")]

    def __init__(self, test_labels, options):
        super(Task, self).__init__(test_labels, options)
        self.test_apps = get_apps_under_test(test_labels, options['test_all'])
        self.output_dir = options['output_dir']
        self.with_migrations = options.get('coverage_with_migrations',
                                    getattr(settings,
                                            'COVERAGE_WITH_MIGRATIONS', False))

        self.html_dir = options.get('coverage_html_report_dir') or \
                            getattr(settings,
                                    'COVERAGE_REPORT_HTML_OUTPUT_DIR', '')

        self.branch = options.get('coverage_measure_branch',
                                  getattr(settings,
                                          'COVERAGE_MEASURE_BRANCH', True))

        self.exclude_locations = []
        modnames = options.get('coverage_excludes') or \
                        getattr(settings, 'COVERAGE_EXCLUDES', [])
        for modname in modnames:
            try:
                self.exclude_locations.append(
                        os.path.dirname(
                            import_module(modname).__file__
                        )
                )
            except ImportError:
                pass

        # Extra folders to exclude. Particularly useful to specify things like
        # apps/company/migrations/*
        self.exclude_locations.extend(
                        getattr(settings, 'COVERAGE_EXCLUDES_FOLDERS', []))
        #import ipdb; ipdb.set_trace()

        self.coverage = Coverage(branch=self.branch,
                                 source=self.test_apps,
                                 omit=self.exclude_locations,
                                 config_file=options.get('coverage_rcfile') or
                                                 Task.default_config_path())

    def setup_test_environment(self, **kwargs):
        self.coverage.start()

    def teardown_test_environment(self, **kwargs):
        self.coverage.stop()

        morfs = [filename for filename in self.coverage.data.measured_files()
                 if self.want_file(filename)]

        if not os.path.exists(self.output_dir):
            os.makedirs(self.output_dir)
        self.coverage.xml_report(morfs=morfs,
                                 outfile=os.path.join(
                                        self.output_dir, 'coverage.xml'))

        if self.html_dir:
            self.coverage.html_report(morfs=morfs, directory=self.html_dir)

    def want_file(self, filename):
        if not self.with_migrations and '/migrations/' in filename:
            return False
        for location in self.exclude_locations:
            if filename.startswith(location):
                return False

        return True

    @staticmethod
    def default_config_path():
        rcfile = getattr(settings, 'COVERAGE_RCFILE', 'coverage.rc')
        if os.path.exists(rcfile):
            return rcfile
        return None