aboutsummaryrefslogtreecommitdiffstats
path: root/test/test_exceptions.py
blob: 2ec46cf42694b93f1a7d522ddc482a1779ba5d41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
# -*- coding: utf-8 -*-
import sys

from mako import compat
from mako import exceptions
from mako.compat import u
from mako.lookup import TemplateLookup
from mako.template import Template
from test import requires_no_pygments_exceptions
from test import requires_pygments_14
from test import TemplateTest
from test.util import result_lines


class ExceptionsTest(TemplateTest):
    def test_html_error_template(self):
        """test the html_error_template"""
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render_unicode()
            assert False
        except exceptions.CompileException:
            html_error = exceptions.html_error_template().render_unicode()
            assert (
                "CompileException: Fragment 'i = 0' is not "
                "a partial control statement at line: 2 char: 1"
            ) in html_error
            assert "<style>" in html_error
            html_error_stripped = html_error.strip()
            assert html_error_stripped.startswith("<html>")
            assert html_error_stripped.endswith("</html>")

            not_full = exceptions.html_error_template().render_unicode(
                full=False
            )
            assert "<html>" not in not_full
            assert "<style>" in not_full

            no_css = exceptions.html_error_template().render_unicode(css=False)
            assert "<style>" not in no_css
        else:
            assert False, (
                "This function should trigger a CompileException, "
                "but didn't"
            )

    def test_text_error_template(self):
        code = """
% i = 0
"""
        try:
            template = Template(code)
            template.render_unicode()
            assert False
        except exceptions.CompileException:
            text_error = exceptions.text_error_template().render_unicode()
            assert "Traceback (most recent call last):" in text_error
            assert (
                "CompileException: Fragment 'i = 0' is not a partial "
                "control statement"
            ) in text_error

    @requires_pygments_14
    def test_utf8_html_error_template_pygments(self):
        """test the html_error_template with a Template containing UTF-8
        chars"""

        if compat.py3k:
            code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
        else:
            code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${u'привет'}
% endif
"""
        try:
            template = Template(code)
            template.render_unicode()
        except exceptions.CompileException:
            html_error = exceptions.html_error_template().render()
            if compat.py3k:
                assert (
                    (
                        "CompileException: Fragment &#39;if 2 == 2: /an "
                        "error&#39; is not a partial control statement "
                        "at line: 2 char: 1"
                    ).encode(sys.getdefaultencoding(), "htmlentityreplace")
                    in html_error
                )
            else:
                assert (
                    "CompileException: Fragment &#39;if 2 == 2: /an "
                    "error&#39; is not a partial control statement "
                    "at line: 2 char: 1"
                ) in html_error

            if compat.py3k:
                assert (
                    "".encode(sys.getdefaultencoding(), "htmlentityreplace")
                    in html_error
                )
            else:
                assert (
                    "&#39;"
                    "&#x43F;&#x440;&#x438;&#x432;&#x435;&#x442;"
                    '&#39;</span><span class="cp">}</span>'.encode(
                        sys.getdefaultencoding(), "htmlentityreplace"
                    )
                    in html_error
                )
        else:
            assert False, (
                "This function should trigger a CompileException, "
                "but didn't"
            )

    @requires_no_pygments_exceptions
    def test_utf8_html_error_template_no_pygments(self):
        """test the html_error_template with a Template containing UTF-8
        chars"""

        if compat.py3k:
            code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${'привет'}
% endif
"""
        else:
            code = """# -*- coding: utf-8 -*-
% if 2 == 2: /an error
${u'привет'}
% endif
"""
        try:
            template = Template(code)
            template.render_unicode()
        except exceptions.CompileException:
            html_error = exceptions.html_error_template().render()
            if compat.py3k:
                assert (
                    (
                        "CompileException: Fragment &#39;if 2 == 2: /an "
                        "error&#39; is not a partial control statement "
                        "at line: 2 char: 1"
                    ).encode(sys.getdefaultencoding(), "htmlentityreplace")
                    in html_error
                )
            else:
                assert (
                    "CompileException: Fragment &#39;if 2 == 2: /an "
                    "error&#39; is not a partial control statement "
                    "at line: 2 char: 1"
                ) in html_error

            if compat.py3k:
                assert (
                    "${&#39;привет&#39;}".encode(
                        sys.getdefaultencoding(), "htmlentityreplace"
                    )
                    in html_error
                )
            else:
                assert (
                    u("${u&#39;привет&#39;}").encode(
                        sys.getdefaultencoding(), "htmlentityreplace"
                    )
                    in html_error
                )
        else:
            assert False, (
                "This function should trigger a CompileException, "
                "but didn't"
            )

    def test_format_closures(self):
        try:
            exec("def foo():" "    raise RuntimeError('test')", locals())
            foo()  # noqa
        except:
            html_error = exceptions.html_error_template().render()
            assert "RuntimeError: test" in str(html_error)

    def test_py_utf8_html_error_template(self):
        try:
            foo = u("日本")  # noqa
            raise RuntimeError("test")
        except:
            html_error = exceptions.html_error_template().render()
            if compat.py3k:
                assert "RuntimeError: test" in html_error.decode("utf-8")
                assert "foo = u(&quot;日本&quot;)" in html_error.decode(
                    "utf-8"
                ) or "foo = u(&#34;日本&#34;)" in html_error.decode("utf-8")
            else:
                assert "RuntimeError: test" in html_error
                assert (
                    "foo = u(&quot;&#x65E5;&#x672C;&quot;)" in html_error
                    or "foo = u(&#34;&#x65E5;&#x672C;&#34;)" in html_error
                )

    def test_py_unicode_error_html_error_template(self):
        try:
            raise RuntimeError(u("日本"))
        except:
            html_error = exceptions.html_error_template().render()
            assert (
                u("RuntimeError: 日本").encode("ascii", "ignore") in html_error
            )

    @requires_pygments_14
    def test_format_exceptions_pygments(self):
        l = TemplateLookup(format_exceptions=True)

        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
${foobar}
        """,
        )

        l.put_string(
            "base.html",
            """
        ${self.body()}
        """,
        )

        assert (
            '<div class="sourceline"><table class="syntax-highlightedtable">'
            in l.get_template("foo.html").render_unicode()
        )

    @requires_no_pygments_exceptions
    def test_format_exceptions_no_pygments(self):
        l = TemplateLookup(format_exceptions=True)

        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
${foobar}
        """,
        )

        l.put_string(
            "base.html",
            """
        ${self.body()}
        """,
        )

        assert '<div class="sourceline">${foobar}</div>' in result_lines(
            l.get_template("foo.html").render_unicode()
        )

    @requires_pygments_14
    def test_utf8_format_exceptions_pygments(self):
        """test that htmlentityreplace formatting is applied to
           exceptions reported with format_exceptions=True"""

        l = TemplateLookup(format_exceptions=True)
        if compat.py3k:
            l.put_string(
                "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
            )
        else:
            l.put_string(
                "foo.html",
                """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""",
            )

        if compat.py3k:
            assert "&#39;привет&#39;</span>" in l.get_template(
                "foo.html"
            ).render().decode("utf-8")
        else:
            assert (
                "&#39;&#x43F;&#x440;&#x438;&#x432;"
                "&#x435;&#x442;&#39;</span>"
            ) in l.get_template("foo.html").render().decode("utf-8")

    @requires_no_pygments_exceptions
    def test_utf8_format_exceptions_no_pygments(self):
        """test that htmlentityreplace formatting is applied to
           exceptions reported with format_exceptions=True"""

        l = TemplateLookup(format_exceptions=True)
        if compat.py3k:
            l.put_string(
                "foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}"""
            )
        else:
            l.put_string(
                "foo.html",
                """# -*- coding: utf-8 -*-\n${u'привет' + foobar}""",
            )

        if compat.py3k:
            assert (
                '<div class="sourceline">${&#39;привет&#39; + foobar}</div>'
                in result_lines(
                    l.get_template("foo.html").render().decode("utf-8")
                )
            )
        else:
            assert (
                "${u&#39;&#x43F;&#x440;&#x438;&#x432;&#x435;"
                "&#x442;&#39; + foobar}"
                in result_lines(
                    l.get_template("foo.html").render().decode("utf-8")
                )
            )

    def test_mod_no_encoding(self):

        mod = __import__("test.foo.mod_no_encoding").foo.mod_no_encoding
        try:
            mod.run()
        except:
            t, v, tback = sys.exc_info()
            exceptions.html_error_template().render_unicode(
                error=v, traceback=tback
            )

    def test_custom_tback(self):
        try:
            raise RuntimeError("error 1")
            foo("bar")  # noqa
        except:
            t, v, tback = sys.exc_info()

        try:
            raise RuntimeError("error 2")
        except:
            html_error = exceptions.html_error_template().render_unicode(
                error=v, traceback=tback
            )

        # obfuscate the text so that this text
        # isn't in the 'wrong' exception
        assert (
            "".join(reversed(");touq&rab;touq&(oof")) in html_error
            or "".join(reversed(");43#&rab;43#&(oof")) in html_error
        )

    def test_tback_no_trace_from_py_file(self):
        try:
            t = self._file_template("runtimeerr.html")
            t.render()
        except:
            t, v, tback = sys.exc_info()

        if not compat.py3k:
            # blow away tracebaack info
            sys.exc_clear()

        # and don't even send what we have.
        html_error = exceptions.html_error_template().render_unicode(
            error=v, traceback=None
        )
        assert (
            "local variable &#39;y&#39; referenced before assignment"
            in html_error
        )

    def test_tback_trace_from_py_file(self):
        t = self._file_template("runtimeerr.html")
        try:
            t.render()
            assert False
        except:
            html_error = exceptions.html_error_template().render_unicode()

        assert (
            "local variable &#39;y&#39; referenced before assignment"
            in html_error
        )

    def test_code_block_line_number(self):
        l = TemplateLookup()
        l.put_string(
            "foo.html",
            """
<%
msg = "Something went wrong."
raise RuntimeError(msg)  # This is the line.
%>
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'File "foo.html", line 4, in render_body' in text_error
            assert "raise RuntimeError(msg)  # This is the line." in text_error
        else:
            assert False

    def test_module_block_line_number(self):
        l = TemplateLookup()
        l.put_string(
            "foo.html",
            """
<%!
def foo():
    msg = "Something went wrong."
    raise RuntimeError(msg)  # This is the line.
%>
${foo()}
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert 'File "foo.html", line 7, in render_body' in text_error
            assert 'File "foo.html", line 5, in foo' in text_error
            assert "raise RuntimeError(msg)  # This is the line." in text_error
        else:
            assert False

    def test_alternating_file_names(self):
        l = TemplateLookup()
        l.put_string(
            "base.html",
            """
<%!
def broken():
    raise RuntimeError("Something went wrong.")
%> body starts here
<%block name="foo">
    ${broken()}
</%block>
            """,
        )
        l.put_string(
            "foo.html",
            """
<%inherit file="base.html"/>
<%block name="foo">
    ${parent.foo()}
</%block>
            """,
        )
        t = l.get_template("foo.html")
        try:
            t.render()
        except:
            text_error = exceptions.text_error_template().render_unicode()
            assert """
  File "base.html", line 5, in render_body
    %> body starts here
  File "foo.html", line 4, in render_foo
    ${parent.foo()}
  File "base.html", line 7, in render_foo
    ${broken()}
  File "base.html", line 4, in broken
    raise RuntimeError("Something went wrong.")
""" in text_error
        else:
            assert False