| 1 |
""" |
| 2 |
Pygments HTML formatter tests |
| 3 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 4 |
|
| 5 |
:copyright: Copyright 2006-present by the Pygments team, see AUTHORS. |
| 6 |
:license: BSD, see LICENSE for details. |
| 7 |
""" |
| 8 |
|
| 9 |
import os |
| 10 |
import re |
| 11 |
import tempfile |
| 12 |
from io import StringIO |
| 13 |
from os import path |
| 14 |
|
| 15 |
import pytest |
| 16 |
|
| 17 |
from pygments.formatters import HtmlFormatter, NullFormatter |
| 18 |
from pygments.formatters.html import escape_html |
| 19 |
from pygments.lexers import PythonLexer |
| 20 |
from pygments.style import Style |
| 21 |
|
| 22 |
TESTDIR = path.dirname(path.abspath(__file__)) |
| 23 |
TESTFILE = path.join(TESTDIR, 'test_html_formatter.py') |
| 24 |
|
| 25 |
with open(TESTFILE, encoding='utf-8') as fp: |
| 26 |
tokensource = list(PythonLexer().get_tokens(fp.read())) |
| 27 |
|
| 28 |
|
| 29 |
def test_correct_output(): |
| 30 |
hfmt = HtmlFormatter(nowrap=True) |
| 31 |
houtfile = StringIO() |
| 32 |
hfmt.format(tokensource, houtfile) |
| 33 |
|
| 34 |
nfmt = NullFormatter() |
| 35 |
noutfile = StringIO() |
| 36 |
nfmt.format(tokensource, noutfile) |
| 37 |
|
| 38 |
stripped_html = re.sub('<.*?>', '', houtfile.getvalue()) |
| 39 |
escaped_text = escape_html(noutfile.getvalue()) |
| 40 |
assert stripped_html == escaped_text |
| 41 |
|
| 42 |
|
| 43 |
def test_external_css(): |
| 44 |
# test correct behavior |
| 45 |
# CSS should be in /tmp directory |
| 46 |
fmt1 = HtmlFormatter(full=True, cssfile='fmt1.css', outencoding='utf-8') |
| 47 |
# CSS should be in TESTDIR (TESTDIR is absolute) |
| 48 |
fmt2 = HtmlFormatter(full=True, cssfile=path.join(TESTDIR, 'fmt2.css'), |
| 49 |
outencoding='utf-8') |
| 50 |
tfile = tempfile.NamedTemporaryFile(suffix='.html') |
| 51 |
fmt1.format(tokensource, tfile) |
| 52 |
try: |
| 53 |
fmt2.format(tokensource, tfile) |
| 54 |
assert path.isfile(path.join(TESTDIR, 'fmt2.css')) |
| 55 |
except OSError: |
| 56 |
# test directory not writable |
| 57 |
pass |
| 58 |
tfile.close() |
| 59 |
|
| 60 |
assert path.isfile(path.join(path.dirname(tfile.name), 'fmt1.css')) |
| 61 |
os.unlink(path.join(path.dirname(tfile.name), 'fmt1.css')) |
| 62 |
try: |
| 63 |
os.unlink(path.join(TESTDIR, 'fmt2.css')) |
| 64 |
except OSError: |
| 65 |
pass |
| 66 |
|
| 67 |
|
| 68 |
def test_all_options(): |
| 69 |
def check(optdict): |
| 70 |
outfile = StringIO() |
| 71 |
fmt = HtmlFormatter(**optdict) |
| 72 |
fmt.format(tokensource, outfile) |
| 73 |
|
| 74 |
for optdict in [ |
| 75 |
dict(nowrap=True), |
| 76 |
dict(linenos=True, full=True), |
| 77 |
dict(linenos=True, linespans='L'), |
| 78 |
dict(hl_lines=[1, 5, 10, 'xxx']), |
| 79 |
dict(hl_lines=[1, 5, 10], noclasses=True), |
| 80 |
]: |
| 81 |
check(optdict) |
| 82 |
|
| 83 |
for linenos in [False, 'table', 'inline']: |
| 84 |
for noclasses in [False, True]: |
| 85 |
for linenospecial in [0, 5]: |
| 86 |
for anchorlinenos in [False, True]: |
| 87 |
optdict = dict( |
| 88 |
linenos=linenos, |
| 89 |
noclasses=noclasses, |
| 90 |
linenospecial=linenospecial, |
| 91 |
anchorlinenos=anchorlinenos, |
| 92 |
) |
| 93 |
check(optdict) |
| 94 |
|
| 95 |
|
| 96 |
def test_linespans(): |
| 97 |
outfile = StringIO() |
| 98 |
fmt = HtmlFormatter(linespans='L', anchorlinenos=True, linenos="inline") |
| 99 |
fmt.format(tokensource, outfile) |
| 100 |
html = outfile.getvalue() |
| 101 |
assert re.search(r"""<span id="L-1">\s*<a href="#L-1"><span\s*class="linenos">\s*1</span></a>""", html) |
| 102 |
|
| 103 |
|
| 104 |
def test_lineanchors(): |
| 105 |
optdict = dict(lineanchors="foo") |
| 106 |
outfile = StringIO() |
| 107 |
fmt = HtmlFormatter(**optdict) |
| 108 |
fmt.format(tokensource, outfile) |
| 109 |
html = outfile.getvalue() |
| 110 |
assert re.search("<pre>\\s*<span>\\s*</span>\\s*<a id=\"foo-1\" name=\"foo-1\" href=\"#foo-1\">", html) |
| 111 |
|
| 112 |
|
| 113 |
def test_lineanchors_with_startnum(): |
| 114 |
optdict = dict(lineanchors="foo", linenostart=5) |
| 115 |
outfile = StringIO() |
| 116 |
fmt = HtmlFormatter(**optdict) |
| 117 |
fmt.format(tokensource, outfile) |
| 118 |
html = outfile.getvalue() |
| 119 |
assert re.search("<pre>\\s*<span>\\s*</span>\\s*<a id=\"foo-5\" name=\"foo-5\" href=\"#foo-5\">", html) |
| 120 |
|
| 121 |
|
| 122 |
def test_valid_output(): |
| 123 |
# test all available wrappers |
| 124 |
fmt = HtmlFormatter(full=True, linenos=True, noclasses=True, |
| 125 |
outencoding='utf-8') |
| 126 |
|
| 127 |
handle, pathname = tempfile.mkstemp('.html') |
| 128 |
with os.fdopen(handle, 'w+b') as tfile: |
| 129 |
fmt.format(tokensource, tfile) |
| 130 |
catname = os.path.join(TESTDIR, 'dtds', 'HTML4.soc') |
| 131 |
try: |
| 132 |
import subprocess |
| 133 |
po = subprocess.Popen(['nsgmls', '-s', '-c', catname, pathname], |
| 134 |
stdout=subprocess.PIPE) |
| 135 |
ret = po.wait() |
| 136 |
output = po.stdout.read() |
| 137 |
po.stdout.close() |
| 138 |
except OSError: |
| 139 |
# nsgmls not available |
| 140 |
pass |
| 141 |
else: |
| 142 |
if ret: |
| 143 |
print(output) |
| 144 |
assert not ret, 'nsgmls run reported errors' |
| 145 |
|
| 146 |
os.unlink(pathname) |
| 147 |
|
| 148 |
|
| 149 |
def test_get_style_defs_contains_pre_style(): |
| 150 |
style_defs = HtmlFormatter().get_style_defs().splitlines() |
| 151 |
assert style_defs[0] == 'pre { line-height: 125%; }' |
| 152 |
|
| 153 |
|
| 154 |
def test_get_style_defs_contains_default_line_numbers_styles(): |
| 155 |
style_defs = HtmlFormatter().get_style_defs().splitlines() |
| 156 |
|
| 157 |
assert style_defs[1] == ( |
| 158 |
'td.linenos .normal ' |
| 159 |
'{ color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }' |
| 160 |
) |
| 161 |
assert style_defs[2] == ( |
| 162 |
'span.linenos ' |
| 163 |
'{ color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }' |
| 164 |
) |
| 165 |
|
| 166 |
|
| 167 |
def test_get_style_defs_contains_style_specific_line_numbers_styles(): |
| 168 |
class TestStyle(Style): |
| 169 |
line_number_color = '#ff0000' |
| 170 |
line_number_background_color = '#0000ff' |
| 171 |
line_number_special_color = '#00ff00' |
| 172 |
line_number_special_background_color = '#ffffff' |
| 173 |
|
| 174 |
style_defs = HtmlFormatter(style=TestStyle).get_style_defs().splitlines() |
| 175 |
|
| 176 |
assert style_defs[1] == ( |
| 177 |
'td.linenos .normal ' |
| 178 |
'{ color: #ff0000; background-color: #0000ff; padding-left: 5px; padding-right: 5px; }' |
| 179 |
) |
| 180 |
assert style_defs[2] == ( |
| 181 |
'span.linenos ' |
| 182 |
'{ color: #ff0000; background-color: #0000ff; padding-left: 5px; padding-right: 5px; }' |
| 183 |
) |
| 184 |
assert style_defs[3] == ( |
| 185 |
'td.linenos .special ' |
| 186 |
'{ color: #00ff00; background-color: #ffffff; padding-left: 5px; padding-right: 5px; }' |
| 187 |
) |
| 188 |
assert style_defs[4] == ( |
| 189 |
'span.linenos.special ' |
| 190 |
'{ color: #00ff00; background-color: #ffffff; padding-left: 5px; padding-right: 5px; }' |
| 191 |
) |
| 192 |
|
| 193 |
|
| 194 |
@pytest.mark.parametrize( |
| 195 |
"formatter_kwargs, style_defs_args, assert_starts_with, assert_contains", |
| 196 |
[ |
| 197 |
[{}, [], ".", []], |
| 198 |
[{"cssclass": "foo"}, [], ".foo .", []], |
| 199 |
[{"cssclass": "foo"}, [".bar"], ".bar .", []], |
| 200 |
[{"cssclass": "foo"}, [[".bar", ".baz"]], ".ba", [".bar .", ".baz ."]], |
| 201 |
] |
| 202 |
) |
| 203 |
def test_get_token_style_defs_uses_css_prefix( |
| 204 |
formatter_kwargs, style_defs_args, assert_starts_with, assert_contains |
| 205 |
): |
| 206 |
formatter = HtmlFormatter(**formatter_kwargs) |
| 207 |
|
| 208 |
for line in formatter.get_token_style_defs(*style_defs_args): |
| 209 |
assert line.startswith(assert_starts_with) |
| 210 |
for s in assert_contains: |
| 211 |
assert s in line |
| 212 |
|
| 213 |
|
| 214 |
def test_get_background_style_defs_uses_multiple_css_prefixes(): |
| 215 |
formatter = HtmlFormatter() |
| 216 |
|
| 217 |
lines = formatter.get_background_style_defs([".foo", ".bar"]) |
| 218 |
assert lines[0].startswith(".foo .hll, .bar .hll {") |
| 219 |
assert lines[1].startswith(".foo , .bar {") |
| 220 |
|
| 221 |
|
| 222 |
def test_unicode_options(): |
| 223 |
fmt = HtmlFormatter(title='Föö', |
| 224 |
cssclass='bär', |
| 225 |
cssstyles='div:before { content: \'bäz\' }', |
| 226 |
encoding='utf-8') |
| 227 |
handle, pathname = tempfile.mkstemp('.html') |
| 228 |
with os.fdopen(handle, 'w+b') as tfile: |
| 229 |
fmt.format(tokensource, tfile) |
| 230 |
|
| 231 |
|
| 232 |
def test_ctags(): |
| 233 |
try: |
| 234 |
import ctags # noqa: F401 |
| 235 |
except ImportError: |
| 236 |
# we can't check without the ctags module, but at least check the exception |
| 237 |
assert pytest.raises( |
| 238 |
RuntimeError, HtmlFormatter, tagsfile='tests/support/tags' |
| 239 |
) |
| 240 |
else: |
| 241 |
# this tagfile says that test_ctags() is on line 165, even if it isn't |
| 242 |
# anymore in the actual source |
| 243 |
fmt = HtmlFormatter(tagsfile='tests/support/tags', lineanchors='L', |
| 244 |
tagurlformat='%(fname)s%(fext)s') |
| 245 |
outfile = StringIO() |
| 246 |
fmt.format(tokensource, outfile) |
| 247 |
assert '<a href="test_html_formatter.py#L-165">test_ctags</a>' \ |
| 248 |
in outfile.getvalue() |
| 249 |
|
| 250 |
|
| 251 |
def test_filename(): |
| 252 |
optdict = dict(filename="test.py") |
| 253 |
outfile = StringIO() |
| 254 |
fmt = HtmlFormatter(**optdict) |
| 255 |
fmt.format(tokensource, outfile) |
| 256 |
html = outfile.getvalue() |
| 257 |
assert re.search("<span class=\"filename\">test.py</span><pre>", html) |
| 258 |
|
| 259 |
|
| 260 |
def test_debug_token_types(): |
| 261 |
fmt_nod_token_types = HtmlFormatter(debug_token_types=False) |
| 262 |
outfile_nod_token_types = StringIO() |
| 263 |
fmt_nod_token_types.format(tokensource, outfile_nod_token_types) |
| 264 |
html_nod_token_types = outfile_nod_token_types.getvalue() |
| 265 |
assert '<span class="n" title="Name">TESTDIR</span>' not in html_nod_token_types |
| 266 |
|
| 267 |
fmt_debug_token_types = HtmlFormatter(debug_token_types=True) |
| 268 |
outfile_debug_token_types = StringIO() |
| 269 |
fmt_debug_token_types.format(tokensource, outfile_debug_token_types) |
| 270 |
html_debug_token_types = outfile_debug_token_types.getvalue() |
| 271 |
assert '<span class="n" title="Name">TESTDIR</span>' in html_debug_token_types |
| •272 |
|
| 273 |
|
| 274 |
def test_html_escape_attributes(): |
| 275 |
"""Test that HTML special characters in formatter option values are properly escaped.""" |
| 276 |
|
| 277 |
fmt = HtmlFormatter( |
| 278 |
cssclass='bad<script>', |
| 279 |
cssstyles='color: "&"', |
| 280 |
filename='<file\'>.py', |
| 281 |
lineseparator='<br>', |
| 282 |
lineanchors='anchor"name', |
| 283 |
linespans='span&name', |
| 284 |
) |
| 285 |
assert fmt.cssclass == 'bad<script>' |
| 286 |
assert fmt.cssstyles == 'color: "&"' |
| 287 |
assert fmt.filename == '<file'>.py' |
| 288 |
assert fmt.lineseparator == '<br>' |
| 289 |
assert fmt.lineanchors == 'anchor"name' |
| 290 |
assert fmt.linespans == 'span&name' |
| 291 |
|
| 292 |
"""Test that None values for these options are handled gracefully.""" |
| 293 |
|
| 294 |
fmt_none = HtmlFormatter( |
| 295 |
cssclass=None, |
| 296 |
cssstyles=None, |
| 297 |
filename=None, |
| 298 |
lineseparator=None, |
| 299 |
lineanchors=None, |
| 300 |
linespans=None, |
| 301 |
) |
| 302 |
assert fmt_none.cssclass == '' |
| 303 |
assert fmt_none.cssstyles == '' |
| 304 |
assert fmt_none.filename == '' |
| 305 |
assert fmt_none.lineseparator == '' |
| 306 |
assert fmt_none.lineanchors == '' |
| 307 |
assert fmt_none.linespans == '' |