Esempio n. 1
0
    def _assert_format(self, src_tokens, src_filename, start_line, violation_lines, expected_fixture):

        snippet = Snippet(src_tokens, src_filename, start_line, violation_lines)
        result = snippet.html()

        expected_str = load_fixture(expected_fixture, encoding="utf-8")

        assert_long_str_equal(expected_str, result, strip=True)
        self.assertTrue(isinstance(result, six.text_type))
Esempio n. 2
0
    def _assert_format(self, src_tokens, src_filename, start_line,
                       violation_lines, expected_fixture):

        snippet = Snippet(src_tokens, src_filename, start_line,
                          violation_lines)
        result = snippet.html()

        expected_str = load_fixture(expected_fixture, encoding='utf-8')

        assert_long_str_equal(expected_str, result, strip=True)
        self.assertTrue(isinstance(result, six.text_type))
Esempio n. 3
0
def _assert_format(
    src_tokens,
    src_filename,
    start_line,
    last_line,
    violation_lines,
    expected_fixture,
):
    snippet = Snippet(src_tokens, src_filename, start_line, last_line,
                      violation_lines, None)
    result = snippet.html()

    expected_str = load_fixture(expected_fixture, encoding="utf-8")

    assert expected_str.strip() == result.strip()
    assert isinstance(result, str)
Esempio n. 4
0
    def test_load_snippets_html(self):

        # Need to be in the fixture directory
        # so the source path is displayed correctly
        old_cwd = os.getcwd()
        self.addCleanup(lambda: os.chdir(old_cwd))
        os.chdir(fixture_path(''))

        src_path = fixture_path('snippet_src.py')
        self._init_src_file(100, src_path)

        # One higher-level test to make sure
        # the snippets are being rendered correctly
        violations = [10, 12, 13, 50, 51, 54, 55, 57]
        snippets_html = '\n\n'.join(
            Snippet.load_snippets_html('snippet_src.py', violations)
        )

        # Load the fixture for the expected contents
        expected_path = fixture_path('snippet_list.html')
        with open(expected_path) as fixture_file:
            expected = fixture_file.read()

        # Check that we got what we expected
        assert_long_str_equal(expected, snippets_html, strip=True)
Esempio n. 5
0
    def _src_path_stats(self, src_path):
        """
        Return a dict of statistics for the source file at `src_path`.
        """

        # Find violation lines
        violation_lines = self.violation_lines(src_path)
        violations = sorted(self._diff_violations()[src_path].violations)

        # Load source snippets (if the report will display them)
        # If we cannot load the file, then fail gracefully
        if self.INCLUDE_SNIPPETS:
            try:
                snippets = Snippet.load_snippets_html(src_path, violation_lines)
            except IOError:
                snippets = []
        else:
            snippets = []

        return {
            'percent_covered': self.percent_covered(src_path),
            'violation_lines': TemplateReportGenerator.combine_adjacent_lines(violation_lines),
            'violations': violations,
            'snippets_html': snippets
        }
Esempio n. 6
0
    def _src_path_stats(self, src_path):

        stats = super()._src_path_stats(src_path)

        # Load source snippets (if the report will display them)
        # If we cannot load the file, then fail gracefully
        formatted_snippets = {"html": [], "markdown": [], "terminal": []}
        if self.include_snippets:
            with contextlib.suppress(OSError):
                formatted_snippets = Snippet.load_formatted_snippets(
                    src_path, stats["violation_lines"])

        stats.update({
            "snippets_html":
            formatted_snippets["html"],
            "snippets_markdown":
            formatted_snippets["markdown"],
            "snippets_terminal":
            formatted_snippets["terminal"],
            "violation_lines":
            TemplateReportGenerator.combine_adjacent_lines(
                stats["violation_lines"]),
        })

        return stats
Esempio n. 7
0
    def _src_path_stats(self, src_path):
        """
        Return a dict of statistics for the source file at `src_path`.
        """

        # Find violation lines
        violation_lines = self.violation_lines(src_path)
        violations = sorted(self._diff_violations()[src_path].violations)

        # Load source snippets (if the report will display them)
        # If we cannot load the file, then fail gracefully
        if self.INCLUDE_SNIPPETS:
            try:
                snippets = Snippet.load_snippets_html(src_path, violation_lines)
            except IOError:
                snippets = []
        else:
            snippets = []

        return {
            'percent_covered': self.percent_covered(src_path),
            'violation_lines': TemplateReportGenerator.combine_adjacent_lines(violation_lines),
            'violations': violations,
            'snippets_html': snippets
        }
Esempio n. 8
0
    def _assert_line_range(self, violation_lines, expected_ranges):
        """
        Assert that the snippets loaded using `violation_lines`
        have the correct ranges of lines.

        `violation_lines` is a list of line numbers containing violations
        (which should get included in snippets).

        `expected_ranges` is a list of `(start, end)` tuples representing
        the starting and ending lines expected in a snippet.
        Line numbers start at 1.
        """

        # Load snippets from the source file
        snippet_list = Snippet.load_snippets(
            self._src_path, violation_lines
        )

        # Check that we got the right number of snippets
        self.assertEqual(len(snippet_list), len(expected_ranges))

        # Check that the snippets have the desired ranges
        for snippet, line_range in zip(snippet_list, expected_ranges):

            # Expect that the line range is correct
            self.assertEqual(snippet.line_range(), line_range)

            # Expect that the source contents are correct
            start, end = line_range
            self.assertEqual(snippet.text(), self._src_lines(start, end))
Esempio n. 9
0
    def _context(self):
        """
        Return the context to pass to the template.

        The context is a dict of the form:

        {
            'css_url': CSS_URL,
            'report_name': REPORT_NAME,
            'diff_name': DIFF_NAME,
            'src_stats': {SRC_PATH: {
                            'percent_covered': PERCENT_COVERED,
                            'violation_lines': [LINE_NUM, ...]
                            }, ... }
            'total_num_lines': TOTAL_NUM_LINES,
            'total_num_violations': TOTAL_NUM_VIOLATIONS,
            'total_percent_covered': TOTAL_PERCENT_COVERED
        }
        """

        # Include snippet style info if we're displaying
        # source code snippets
        if self.INCLUDE_SNIPPETS:
            snippet_style = Snippet.style_defs()
        else:
            snippet_style = None

        context = super().report_dict()
        context.update({
            "css_url": self.css_url,
            "snippet_style": snippet_style
        })

        return context
Esempio n. 10
0
    def _assert_line_range(self, violation_lines, expected_ranges):
        """
        Assert that the snippets loaded using `violation_lines`
        have the correct ranges of lines.

        `violation_lines` is a list of line numbers containing violations
        (which should get included in snippets).

        `expected_ranges` is a list of `(start, end)` tuples representing
        the starting and ending lines expected in a snippet.
        Line numbers start at 1.
        """

        # Load snippets from the source file
        snippet_list = Snippet.load_snippets(
            self._src_path, violation_lines
        )

        # Check that we got the right number of snippets
        self.assertEqual(len(snippet_list), len(expected_ranges))

        # Check that the snippets have the desired ranges
        for snippet, line_range in zip(snippet_list, expected_ranges):

            # Expect that the line range is correct
            self.assertEqual(snippet.line_range(), line_range)

            # Expect that the source contents are correct
            start, end = line_range
            self.assertEqual(snippet.text(), self._src_lines(start, end))
Esempio n. 11
0
    def _src_path_stats(self, src_path):

        stats = super()._src_path_stats(src_path)

        # Load source snippets (if the report will display them)
        # If we cannot load the file, then fail gracefully
        formatted_snippets = {"html": [], "markdown": []}
        if self.INCLUDE_SNIPPETS:
            try:
                formatted_snippets = Snippet.load_formatted_snippets(
                    src_path, stats["violation_lines"])
            except OSError:
                pass

        stats.update({
            "snippets_html":
            formatted_snippets["html"],
            "snippets_markdown":
            formatted_snippets["markdown"],
            "violation_lines":
            TemplateReportGenerator.combine_adjacent_lines(
                stats["violation_lines"]),
        })

        return stats
Esempio n. 12
0
    def test_style_defs(self):
        style_str = Snippet.style_defs()
        expected_styles = load_fixture(self.FIXTURES['style']).strip()

        # Check that a sample of the styles are present
        # (use only a sample to make the test more robust
        # against Pygment changes).
        for expect_line in expected_styles.split('\n'):
            self.assertIn(expect_line, style_str)
Esempio n. 13
0
    def _assert_format(
        self,
        src_tokens,
        src_filename,
        start_line,
        last_line,
        violation_lines,
        expected_fixture,
    ):

        snippet = Snippet(src_tokens, src_filename, start_line, last_line,
                          violation_lines, None)
        result = snippet.html()

        expected_str = load_fixture(expected_fixture, encoding="utf-8")

        assert_long_str_equal(expected_str, result, strip=True)
        self.assertIsInstance(result, str)
Esempio n. 14
0
    def test_style_defs(self):
        style_str = Snippet.style_defs()
        expected_styles = load_fixture(self.FIXTURES['style']).strip()

        # Check that a sample of the styles are present
        # (use only a sample to make the test more robust
        # against Pygment changes).
        for expect_line in expected_styles.split('\n'):
            self.assertIn(expect_line, style_str)
Esempio n. 15
0
def test_style_defs():
    style_str = Snippet.style_defs()
    expected_styles = load_fixture("snippet.css").strip()

    # Check that a sample of the styles are present
    # (use only a sample to make the test more robust
    # against Pygments changes).
    for expect_line in expected_styles.split("\n"):
        assert expect_line in style_str
Esempio n. 16
0
def _compare_snippets_output(format_, filename, violations,
                             expected_out_filename):
    # One higher-level test to make sure
    # the snippets are being rendered correctly
    formatted_snippets = Snippet.load_formatted_snippets(filename, violations)
    snippets_selected = "\n\n".join(formatted_snippets[format_])
    # Load the fixture for the expected contents
    expected_path = fixture_path(expected_out_filename)
    with open(expected_path, encoding="utf-8") as fixture_file:
        expected = fixture_file.read()
        if isinstance(expected, bytes):
            expected = expected.decode("utf-8")

    # Check that we got what we expected
    assert expected.strip() == snippets_selected.strip()
Esempio n. 17
0
    def test_load_snippets_non_ascii(self):

        # Need to be in the fixture directory
        # so the source path is displayed correctly
        old_cwd = os.getcwd()
        self.addCleanup(lambda: os.chdir(old_cwd))
        os.chdir(fixture_path(''))

        src_path = fixture_path('snippet_src.py')
        self._init_src_file(100, src_path)

        # One higher-level test to make sure
        # the snippets are being rendered correctly
        violations = [10, 12, 13, 50, 51, 54, 55, 57]
        snippets_html = '\n\n'.join(
            Snippet.load_snippets_html('snippet_non_ascii.py', violations)
        )
Esempio n. 18
0
    def _compare_snippets_html_output(self, filename, violations, expected_out_filename):
        # Need to be in the fixture directory
        # so the source path is displayed correctly
        old_cwd = os.getcwd()
        self.addCleanup(lambda: os.chdir(old_cwd))
        os.chdir(fixture_path(""))

        # One higher-level test to make sure
        # the snippets are being rendered correctly
        snippets_html = "\n\n".join(Snippet.load_snippets_html(filename, violations))
        # Load the fixture for the expected contents
        expected_path = fixture_path(expected_out_filename)
        with open(expected_path) as fixture_file:
            expected = fixture_file.read()
            if isinstance(expected, six.binary_type):
                expected = expected.decode("utf-8")

        # Check that we got what we expected
        assert_long_str_equal(expected, snippets_html, strip=True)
Esempio n. 19
0
    def _context(self):
        """
        Return the context to pass to the template.

        The context is a dict of the form:

        {
            'css_url': CSS_URL,
            'report_name': REPORT_NAME,
            'diff_name': DIFF_NAME,
            'src_stats': {SRC_PATH: {
                            'percent_covered': PERCENT_COVERED,
                            'violation_lines': [LINE_NUM, ...]
                            }, ... }
            'total_num_lines': TOTAL_NUM_LINES,
            'total_num_violations': TOTAL_NUM_VIOLATIONS,
            'total_percent_covered': TOTAL_PERCENT_COVERED
        }
        """

        # Calculate the information to pass to the template
        src_stats = {
            src: self._src_path_stats(src)
            for src in self.src_paths()
        }

        # Include snippet style info if we're displaying
        # source code snippets
        if self.INCLUDE_SNIPPETS:
            snippet_style = Snippet.style_defs()
        else:
            snippet_style = None

        return {
            'css_url': self.css_url,
            'report_name': self.coverage_report_name(),
            'diff_name': self.diff_report_name(),
            'src_stats': src_stats,
            'total_num_lines': self.total_num_lines(),
            'total_num_violations': self.total_num_violations(),
            'total_percent_covered': self.total_percent_covered(),
            'snippet_style': snippet_style
        }
Esempio n. 20
0
    def _context(self):
        """
        Return the context to pass to the template.

        The context is a dict of the form:

        {
            'css_url': CSS_URL,
            'report_name': REPORT_NAME,
            'diff_name': DIFF_NAME,
            'src_stats': {SRC_PATH: {
                            'percent_covered': PERCENT_COVERED,
                            'violation_lines': [LINE_NUM, ...]
                            }, ... }
            'total_num_lines': TOTAL_NUM_LINES,
            'total_num_violations': TOTAL_NUM_VIOLATIONS,
            'total_percent_covered': TOTAL_PERCENT_COVERED
        }
        """

        # Calculate the information to pass to the template
        src_stats = dict(
            (src, self._src_path_stats(src)) for src in self.src_paths()
        )

        # Include snippet style info if we're displaying
        # source code snippets
        if self.INCLUDE_SNIPPETS:
            snippet_style = Snippet.style_defs()
        else:
            snippet_style = None

        return {
            'css_url': self.css_url,
            'report_name': self.coverage_report_name(),
            'diff_name': self.diff_report_name(),
            'src_stats': src_stats,
            'total_num_lines': self.total_num_lines(),
            'total_num_violations': self.total_num_violations(),
            'total_percent_covered': self.total_percent_covered(),
            'snippet_style': snippet_style
        }
Esempio n. 21
0
    def _compare_snippets_html_output(self, filename, violations, expected_out_filename):
        # Need to be in the fixture directory
        # so the source path is displayed correctly
        old_cwd = os.getcwd()
        self.addCleanup(lambda: os.chdir(old_cwd))
        os.chdir(fixture_path(''))

        # One higher-level test to make sure
        # the snippets are being rendered correctly
        snippets_html = '\n\n'.join(
            Snippet.load_snippets_html(filename, violations)
        )
        # Load the fixture for the expected contents
        expected_path = fixture_path(expected_out_filename)
        with open(expected_path) as fixture_file:
            expected = fixture_file.read()
            if isinstance(expected, six.binary_type):
                expected = expected.decode('utf-8')

        # Check that we got what we expected
        assert_long_str_equal(expected, snippets_html, strip=True)
Esempio n. 22
0
    def _compare_snippets_output(self, format, filename, violations,
                                 expected_out_filename):
        # Need to be in the fixture directory
        # so the source path is displayed correctly
        old_cwd = os.getcwd()
        self.addCleanup(lambda: os.chdir(old_cwd))
        os.chdir(fixture_path(""))

        # One higher-level test to make sure
        # the snippets are being rendered correctly
        formatted_snippets = Snippet.load_formatted_snippets(
            filename, violations)
        snippets_selected = "\n\n".join(formatted_snippets[format])
        # Load the fixture for the expected contents
        expected_path = fixture_path(expected_out_filename)
        with open(expected_path, encoding="utf-8") as fixture_file:
            expected = fixture_file.read()
            if isinstance(expected, bytes):
                expected = expected.decode("utf-8")

        # Check that we got what we expected
        assert_long_str_equal(expected, snippets_selected, strip=True)
Esempio n. 23
0
    def _src_path_stats(self, src_path):

        stats = super()._src_path_stats(src_path)

        # Load source snippets (if the report will display them)
        # If we cannot load the file, then fail gracefully
        if self.INCLUDE_SNIPPETS:
            try:
                snippets = Snippet.load_snippets_html(src_path,
                                                      stats["violation_lines"])
            except OSError:
                snippets = []
        else:
            snippets = []

        stats.update({
            "snippets_html":
            snippets,
            "violation_lines":
            TemplateReportGenerator.combine_adjacent_lines(
                stats["violation_lines"]),
        })

        return stats
Esempio n. 24
0
def test_latin_one_undeclared(tmp_path):
    file = tmp_path / "tmp"
    file.write_bytes("I am some latin 1 Â encoded text".encode("latin1"))

    contents = Snippet.load_contents(str(file))
    assert contents == "I am some latin 1 Â encoded text"
Esempio n. 25
0
def test_format_with_invalid_start_line():
    for start_line in [-2, -1, 0]:
        with pytest.raises(ValueError):
            Snippet("# test", "test.py", start_line, start_line + 1, [], None)
Esempio n. 26
0
 def test_latin_one_undeclared(self):
     with tempfile.NamedTemporaryFile() as temp:
         temp.write("I am some latin 1 Â encoded text".encode("latin1"))
         temp.flush()
         contents = Snippet.load_contents(temp.name)
     self.assertEqual(contents, "I am some latin 1 Â encoded text")
Esempio n. 27
0
 def test_format_with_invalid_start_line(self):
     for start_line in [-2, -1, 0]:
         with self.assertRaises(ValueError):
             Snippet('# test', 'test.py', start_line, [])