Skip to content

Allow ignoring script tags. #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,18 @@ If you use ``pyproject.toml`` for tool configuration use::
[tool.coverage.django_coverage_plugin]
template_extensions = 'html, txt, tex, email'

By default, <script> tags will be marked as covered if they were rendered. If you are collecting
in-browser coverage data, you can instruct the plugin not to count the content of the script tags
as covered::

[run]
plugins = django_coverage_plugin

[django_coverage_plugin]
ignore_script_tags = true



Caveats
~~~~~~~

Expand Down
53 changes: 51 additions & 2 deletions django_coverage_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@

import os.path
import re
import html.parser

try:
from coverage.exceptions import NoSource
Expand Down Expand Up @@ -158,6 +159,8 @@ def __init__(self, options):

self.source_map = {}

self.ignore_script_tags = options.get('ignore_script_tags', False) in (True, 'True', 'true')

# --- CoveragePlugin methods

def sys_info(self):
Expand All @@ -184,7 +187,7 @@ def file_tracer(self, filename):
return None

def file_reporter(self, filename):
return FileReporter(filename)
return FileReporter(filename, ignore_script_tags=self.ignore_script_tags)

def find_executable_files(self, src_dir):
# We're only interested in files that look like reasonable HTML
Expand Down Expand Up @@ -291,12 +294,48 @@ def get_line_map(self, filename):
return self.source_map[filename]


class ScriptParser(html.parser.HTMLParser):
# We never have nested script tags, so we are all good.

def __init__(self, *args, **kwargs):
self.script_checker = kwargs.pop('script_checker', lambda attrs: True)
super().__init__(*args, **kwargs)
self.script_blocks = []
self.in_script = False
self.script_lines_cache = None

def handle_starttag(self, tag, attrs):
if tag == 'script':
attrs = dict(attrs)
self.in_script = self.script_checker(attrs) and attrs.get('type', 'text/javascript') == 'text/javascript'

def handle_endtag(self, tag):
if tag == 'script':
self.in_script = False

def handle_data(self, data):
if self.in_script:
start_line = self.getpos()[0]
self.script_blocks.append((start_line + 1, start_line + 1 + data.rstrip().count('\n')))

def _script_lines(self):
for block in self.script_blocks:
yield from range(block[0], block[1])

@property
def script_lines(self):
if self.script_lines_cache is None:
self.script_lines_cache = list(self._script_lines())
return self.script_lines_cache


class FileReporter(coverage.plugin.FileReporter):
def __init__(self, filename):
def __init__(self, filename, *, ignore_script_tags=False):
super().__init__(filename)
# TODO: html filenames are absolute.

self._source = None
self.ignore_script_tags = ignore_script_tags

def source(self):
if self._source is None:
Expand All @@ -306,6 +345,16 @@ def source(self):
raise NoSource(f"Couldn't read {self.filename}: {exc}")
return self._source

def translate_lines(self, lines):
if self.ignore_script_tags:
# Initially, we'll only support "simple" script contents, ie,
# they may not have any django template directives within them.
parser = ScriptParser()
parser.feed(self.source())
return {line for line in lines if line not in parser.script_lines}

return super().translate_lines(lines)

def lines(self):
source_lines = set()

Expand Down
64 changes: 64 additions & 0 deletions tests/test_simple.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,70 @@ def test_with(self):
self.assertEqual(text, "\nalpha = 1, beta = 2.\n\n")
self.assert_analysis([1, 2])

def test_script_tag_ignored(self):
self.make_file(".coveragerc", """\
[run]
plugins = django_coverage_plugin
[django_coverage_plugin]
ignore_script_tags = true
""")

template = """{% if 1 %}
{% url 'xxx' as yyy %}
<div class="x"
id="y"
{% if qux %}data-element="true"{% endif %}>
xxx

</div>
<script>
this should be a JS error.
and these lines should not be covered.


</script>
{% endif %}
<div>
yyy
</div>"""
self.make_template(template)
self.run_django_coverage()
report = self.cov.report()
lines = len(template.split('\n'))
self.assertEqual(report, 100.0 * (lines - 2) / lines)

def test_script_tag_not_ignored(self):
self.make_file(".coveragerc", """\
[run]
plugins = django_coverage_plugin
[django_coverage_plugin]
ignore_script_tags = false
""")

template = """{% if 1 %}
{% url 'xxx' as yyy %}
<div class="x"
id="y"
{% if qux %}data-element="true"{% endif %}>
xxx

</div>
<script>
this should be a JS error.
and these lines should not be covered.


</script>
{% endif %}
<div>
yyy
</div>"""
self.make_template(template)
self.run_django_coverage()
report = self.cov.report()
lines = len(template.split('\n'))
self.assertEqual(report, 100.0)


class StringTemplateTest(DjangoPluginTestCase):

Expand Down