Coverage for tdom/processor_test.py: 99%
1138 statements
« prev ^ index » next coverage.py v7.16.0, created at 2026-10-31 18:53 +0000
« prev ^ index » next coverage.py v7.16.0, created at 2026-10-31 18:53 +0000
1import datetime
2import math
3import re
4import typing as t
5from collections import UserDict
6from collections.abc import Callable
7from dataclasses import dataclass
8from itertools import chain, product
9from string.templatelib import Template
11import pytest
12from markupsafe import Markup
13from markupsafe import escape as markupsafe_escape
15from .callables import get_callable_info
16from .escaping import escape_html_text
17from .processor import (
18 AttributeProcessingError,
19 CachedTemplateParserProxy,
20 ComponentProcessingError,
21 ProcessContext,
22 TemplateParserProxy,
23 TemplateProcessor,
24 TextProcessingError,
25 _make_default_template_processor,
26)
27from .processor import (
28 _prep_component_kwargs as prep_component_kwargs,
29)
30from .protocols import HasHTMLDunder
32processor_api = _make_default_template_processor(
33 parser_api=TemplateParserProxy(), # do not use cache
34)
37def make_ctx(**kwargs):
38 return ProcessContext(**kwargs)
41def html(template: Template, assume_ctx: ProcessContext | None = None):
42 if assume_ctx is None:
43 assume_ctx = ProcessContext()
44 return processor_api.process(template, assume_ctx=assume_ctx)
47# --------------------------------------------------------------------------
48# Basic HTML parsing tests
49# --------------------------------------------------------------------------
52#
53# Text
54#
55class TestBareTemplate:
56 def test_empty(self):
57 assert html(t"") == ""
59 def test_text_literal(self):
60 assert html(t"Hello, world!") == "Hello, world!"
62 def test_text_singleton(self):
63 greeting = "Hello, Alice!"
64 assert html(t"{greeting}", make_ctx(parent_tag="div")) == "Hello, Alice!"
65 assert html(t"{greeting}", make_ctx(parent_tag="script")) == "Hello, Alice!"
66 assert html(t"{greeting}", make_ctx(parent_tag="style")) == "Hello, Alice!"
67 assert html(t"{greeting}", make_ctx(parent_tag="textarea")) == "Hello, Alice!"
68 assert html(t"{greeting}", make_ctx(parent_tag="title")) == "Hello, Alice!"
70 def test_text_singleton_without_parent(self):
71 greeting = "</script>"
72 res = html(t"{greeting}")
73 assert res == "</script>"
74 assert res != greeting
76 def test_text_singleton_explicit_parent_script(self):
77 greeting = "</script>"
78 res = html(t"{greeting}", assume_ctx=make_ctx(parent_tag="script"))
79 assert res == "\\x3c/script>"
80 assert res != "</script>"
82 def test_text_singleton_explicit_parent_div(self):
83 greeting = "</div>"
84 res = html(t"{greeting}", assume_ctx=make_ctx(parent_tag="div"))
85 assert res == "</div>"
86 assert res != "</div>"
88 def test_text_template(self):
89 name = "Alice"
90 assert (
91 html(t"Hello, {name}!", assume_ctx=make_ctx(parent_tag="div"))
92 == "Hello, Alice!"
93 )
95 def test_text_template_escaping(self):
96 name = "Alice & Bob"
97 assert (
98 html(t"Hello, {name}!", assume_ctx=make_ctx(parent_tag="div"))
99 == "Hello, Alice & Bob!"
100 )
102 def test_parse_entities_are_escaped_no_parent_tag(self):
103 res = html(t"</p>")
104 assert res == "</p>", "Default to standard escaping."
107class LiteralHTML:
108 """Text is returned as is by __html__."""
110 def __init__(self, text):
111 self.text = text
113 def __html__(self):
114 # In a real app, this would come from a sanitizer or trusted source
115 return self.text
118def test_literal_html_has_html_dunder():
119 assert isinstance(LiteralHTML, HasHTMLDunder)
122def test_markup_has_html_dunder():
123 assert isinstance(Markup, HasHTMLDunder)
126class TestComment:
127 def test_literal(self):
128 assert html(t"<!--This is a comment-->") == "<!--This is a comment-->"
130 #
131 # Singleton / Exact Match
132 #
133 def test_singleton_str(self):
134 text = "This is a comment"
135 assert html(t"<!--{text}-->") == "<!--This is a comment-->"
137 def test_singleton_object(self):
138 assert html(t"<!--{0}-->") == "<!--0-->"
140 def test_singleton_none(self):
141 assert html(t"<!--{None}-->") == "<!---->"
143 @pytest.mark.parametrize("bool_value", (True, False))
144 def test_singleton_bool(self, bool_value):
145 assert html(t"<!--{bool_value}-->") == "<!---->"
147 @pytest.mark.parametrize(
148 "html_dunder_cls",
149 (
150 LiteralHTML,
151 Markup,
152 ),
153 )
154 def test_singleton_has_html_dunder(self, html_dunder_cls):
155 content = html_dunder_cls("-->")
156 assert html(t"<!--{content}-->") == "<!---->-->", (
157 "DO NOT DO THIS! This is just an advanced escape hatch."
158 )
160 def test_singleton_escaping(self):
161 text = "-->comment"
162 assert html(t"<!--{text}-->") == "<!---->comment-->"
164 #
165 # Templated -- literal text mixed with interpolation(s)
166 #
167 def test_templated_str(self):
168 text = "comment"
169 assert html(t"<!--This is a {text}-->") == "<!--This is a comment-->"
171 def test_templated_object(self):
172 assert html(t"<!--This is a {0}-->") == "<!--This is a 0-->"
174 def test_templated_none(self):
175 assert html(t"<!--This is a {None}-->") == "<!--This is a -->"
177 @pytest.mark.parametrize("bool_value", (True, False))
178 def test_templated_bool(self, bool_value):
179 assert html(t"<!--This is a {bool_value}-->") == "<!--This is a -->"
181 @pytest.mark.parametrize(
182 "html_dunder_cls",
183 (
184 LiteralHTML,
185 Markup,
186 ),
187 )
188 def test_templated_has_html_dunder_error(self, html_dunder_cls):
189 """Objects with __html__ are not processed with literal text or other interpolations."""
190 text = html_dunder_cls("in a comment")
191 with pytest.raises(TextProcessingError, match="not supported"):
192 _ = html(t"<!--This is a {text}-->")
193 with pytest.raises(TextProcessingError, match="not supported"):
194 _ = html(t"<!--{None}{text}-->")
195 with pytest.raises(TextProcessingError, match="not supported"):
196 _ = html(t"<!--This is a {Markup('Also check specialized cls.')}-->")
198 def test_templated_multiple_interpolations(self):
199 text = "comment"
200 assert (
201 html(t"<!--This is a {text} with {0} and {None}-->")
202 == "<!--This is a comment with 0 and -->"
203 )
205 def test_templated_escaping(self):
206 # @TODO: There doesn't seem to be a way to properly escape this
207 # so we just use an entity to break the special closing string
208 # even though it won't be actually unescaped by anything. There
209 # might be something better for this.
210 text = "-->comment"
211 assert html(t"<!--This is a {text}-->") == "<!--This is a -->comment-->"
213 def test_not_supported__recursive_template_error(self):
214 text_t = t"comment"
215 with pytest.raises(TextProcessingError, match="not supported"):
216 _ = html(t"<!--{text_t}-->")
218 def test_not_supported_recursive_iterable_error(self):
219 texts = ["This", "is", "a", "comment"]
220 with pytest.raises(TextProcessingError, match="not supported"):
221 _ = html(t"<!--{texts}-->")
224class TestDocumentType:
225 def test_literal(self):
226 assert html(t"<!doctype html>") == "<!DOCTYPE html>"
228 def test_literal_lowercase(self):
229 tp = TemplateProcessor(uppercase_doctype=False)
230 assert (
231 tp.process(t"<!doctype html>", assume_ctx=ProcessContext())
232 == "<!doctype html>"
233 )
236class TestVoidElementLiteral:
237 def test_void(self):
238 assert html(t"<br>") == "<br />"
240 def test_void_self_closed(self):
241 assert html(t"<br />") == "<br />"
243 def test_void_mixed_closing(self):
244 assert html(t"<br>Is this content?<br />") == "<br />Is this content?<br />"
246 def test_chain_of_void_elements(self):
247 # Make sure our handling of CPython issue #69445 is reasonable.
248 assert (
249 html(t"<br><hr><img src='image.png' /><br /><hr>")
250 == '<br /><hr /><img src="image.png" /><br /><hr />'
251 )
254class TestNormalTextElementLiteral:
255 def test_empty(self):
256 assert html(t"<div></div>") == "<div></div>"
258 def test_with_text(self):
259 assert html(t"<p>Hello, world!</p>") == "<p>Hello, world!</p>"
261 def test_nested_elements(self):
262 assert (
263 html(t"<div><p>Hello</p><p>World</p></div>")
264 == "<div><p>Hello</p><p>World</p></div>"
265 )
267 def test_entities_are_escaped(self):
268 """Literal entities interpreted by parser but escaped in output."""
269 res = html(t"<p></p></p>")
270 assert res == "<p></p></p>", res
273class TestNormalTextElementDynamic:
274 def test_singleton_None(self):
275 assert html(t"<p>{None}</p>") == "<p></p>"
277 def test_singleton_str(self):
278 name = "Alice"
279 assert html(t"<p>{name}</p>") == "<p>Alice</p>"
281 @pytest.mark.parametrize("bool_value", (True, False))
282 def test_singleton_bool(self, bool_value):
283 assert html(t"<p>{bool_value}</p>") == "<p></p>"
285 def test_singleton_object(self):
286 assert html(t"<p>{0}</p>") == "<p>0</p>"
288 @pytest.mark.parametrize(
289 "html_dunder_cls",
290 (
291 LiteralHTML,
292 Markup,
293 ),
294 )
295 def test_singleton_has_html_dunder(self, html_dunder_cls):
296 content = html_dunder_cls("<em>Alright!</em>")
297 assert html(t"<p>{content}</p>") == "<p><em>Alright!</em></p>"
299 def test_singleton_simple_template(self):
300 name = "Alice"
301 text_t = t"Hi {name}"
302 assert html(t"<p>{text_t}</p>") == "<p>Hi Alice</p>"
304 def test_singleton_simple_iterable(self):
305 strs = ["Strings", "...", "Yeah!", "Rock", "...", "Yeah!"]
306 assert html(t"<p>{strs}</p>") == "<p>Strings...Yeah!Rock...Yeah!</p>"
308 def test_singleton_escaping(self):
309 text = '''<>&'"'''
310 assert html(t"<p>{text}</p>") == "<p><>&'"</p>"
312 def test_templated_None(self):
313 assert html(t"<p>Response: {None}.</p>") == "<p>Response: .</p>"
315 def test_templated_str(self):
316 name = "Alice"
317 assert html(t"<p>Response: {name}.</p>") == "<p>Response: Alice.</p>"
319 @pytest.mark.parametrize("bool_value", (True, False))
320 def test_templated_bool(self, bool_value):
321 assert html(t"<p>Response: {bool_value}</p>") == "<p>Response: </p>"
323 def test_templated_object(self):
324 assert html(t"<p>Response: {0}.</p>") == "<p>Response: 0.</p>"
326 @pytest.mark.parametrize(
327 "html_dunder_cls",
328 (
329 LiteralHTML,
330 Markup,
331 ),
332 )
333 def test_templated_has_html_dunder(self, html_dunder_cls):
334 text = html_dunder_cls("<em>Alright!</em>")
335 assert (
336 html(t"<p>Response: {text}.</p>") == "<p>Response: <em>Alright!</em>.</p>"
337 )
339 def test_templated_simple_template(self):
340 name = "Alice"
341 text_t = t"Hi {name}"
342 assert html(t"<p>Response: {text_t}.</p>") == "<p>Response: Hi Alice.</p>"
344 def test_templated_simple_iterable(self):
345 strs = ["Strings", "...", "Yeah!", "Rock", "...", "Yeah!"]
346 assert (
347 html(t"<p>Response: {strs}.</p>")
348 == "<p>Response: Strings...Yeah!Rock...Yeah!.</p>"
349 )
351 def test_templated_escaping(self):
352 text = '''<>&'"'''
353 assert (
354 html(t"<p>Response: {text}.</p>")
355 == "<p>Response: <>&'".</p>"
356 )
358 def test_templated_escaping_in_literals(self):
359 text = "This text is fine"
360 assert (
361 html(t"<p>The literal has < in it: {text}.</p>")
362 == "<p>The literal has < in it: This text is fine.</p>"
363 )
365 def test_iterable_of_templates(self):
366 items = ["Apple", "Banana", "Cherry"]
367 assert (
368 html(t"<ul>{[t'<li>{item}</li>' for item in items]}</ul>")
369 == "<ul><li>Apple</li><li>Banana</li><li>Cherry</li></ul>"
370 )
372 def test_iterable_of_templates_of_iterable_of_templates(self):
373 outer = ["fruit", "more fruit"]
374 inner = ["apple", "banana", "cherry"]
375 inner_items = [t"<li>{item}</li>" for item in inner]
376 outer_items = [
377 t"<li>{category}<ul>{inner_items}</ul></li>" for category in outer
378 ]
379 assert (
380 html(t"<ul>{outer_items}</ul>")
381 == "<ul><li>fruit<ul><li>apple</li><li>banana</li><li>cherry</li></ul></li><li>more fruit<ul><li>apple</li><li>banana</li><li>cherry</li></ul></li></ul>"
382 )
385class TestRawTextElementLiteral:
386 def test_script_empty(self):
387 assert html(t"<script></script>") == "<script></script>"
389 def test_style_empty(self):
390 assert html(t"<style></style>") == "<style></style>"
392 def test_script_with_content(self):
393 assert html(t"<script>var x = 1;</script>") == "<script>var x = 1;</script>"
395 def test_style_with_content(self):
396 # @NOTE: Double {{ and }} to avoid t-string interpolation.
397 assert (
398 html(t"<style>.red { color: red; } </style>")
399 == "<style>.red { color: red; }</style>"
400 )
402 def test_script_with_content_escaped_in_normal_text(self):
403 # @NOTE: Double {{ and }} to avoid t-string interpolation.
404 assert (
405 html(t"<script>function CompareNumbers(a, b) { return a < b; } </script>")
406 == "<script>function CompareNumbers(a, b) { return a < b; }</script>"
407 ), "The < should not be escaped."
409 def test_style_with_content_escaped_in_normal_text(self):
410 # @NOTE: Double {{ and }} to avoid t-string interpolation.
411 assert (
412 html(t"<style>section > h4 { background-color: red; } </style>")
413 == "<style>section > h4 { background-color: red; }</style>"
414 ), "The > should not be escaped."
416 def test_not_supported_recursive_template_error(self):
417 text_t = t"comment"
418 with pytest.raises(TextProcessingError, match="not supported"):
419 _ = html(t"<!--{text_t}-->")
421 def test_not_supported_recursive_iterable_error(self):
422 texts = ["This", "is", "a", "comment"]
423 with pytest.raises(TextProcessingError, match="not supported"):
424 _ = html(t"<!--{texts}-->")
427class TestEscapableRawTextElementLiteral:
428 def test_title_empty(self):
429 assert html(t"<title></title>") == "<title></title>"
431 def test_textarea_empty(self):
432 assert html(t"<textarea></textarea>") == "<textarea></textarea>"
434 def test_title_with_content(self):
435 assert html(t"<title>Content</title>") == "<title>Content</title>"
437 def test_textarea_with_content(self):
438 assert html(t"<textarea>Content</textarea>") == "<textarea>Content</textarea>"
440 def test_title_with_escapable_content(self):
441 assert (
442 html(t"<title>Are t-strings > everything?</title>")
443 == "<title>Are t-strings > everything?</title>"
444 ), "The > can be escaped in this content type."
446 def test_textarea_with_escapable_content(self):
447 assert (
448 html(t"<textarea><p>Welcome To TDOM</p></textarea>")
449 == "<textarea><p>Welcome To TDOM</p></textarea>"
450 ), "The p tags can be escaped in this content type."
453class TestRawTextScriptDynamic:
454 def test_singleton_none(self):
455 assert html(t"<script>{None}</script>") == "<script></script>"
457 def test_singleton_str(self):
458 content = "var x = 1;"
459 assert html(t"<script>{content}</script>") == "<script>var x = 1;</script>"
461 @pytest.mark.parametrize("bool_value", (True, False))
462 def test_singleton_bool(self, bool_value):
463 assert html(t"<script>{bool_value}</script>") == "<script></script>"
465 def test_singleton_object(self):
466 content = 0
467 assert html(t"<script>{content}</script>") == "<script>0</script>"
469 @pytest.mark.parametrize(
470 "html_dunder_cls",
471 (
472 LiteralHTML,
473 Markup,
474 ),
475 )
476 def test_singleton_has_html_dunder_pitfall(self, html_dunder_cls):
477 # @TODO: We should probably put some double override to prevent this by accident.
478 # Or just disable this and if people want to do this then put the
479 # content in a SCRIPT and inject the whole thing with a __html__?
480 content = html_dunder_cls("</script>")
481 assert html(t"<script>{content}</script>") == "<script></script></script>", (
482 "DO NOT DO THIS! This is just an advanced escape hatch! Use a data attribute and parseJSON!"
483 )
485 def test_singleton_escaping(self):
486 content = "</script>"
487 script_t = t"<script>{content}</script>"
488 bad_output = script_t.strings[0] + content + script_t.strings[1]
489 assert html(script_t) == "<script>\\x3c/script></script>"
490 assert html(script_t) != bad_output, "Sanity check."
492 def test_templated_none(self):
493 assert (
494 html(t"<script>var x = 1;{None};</script>")
495 == "<script>var x = 1;;</script>"
496 )
498 def test_templated_str(self):
499 content = "var x = 1"
500 assert (
501 html(t"<script>var x = 0;{content};</script>")
502 == "<script>var x = 0;var x = 1;</script>"
503 )
505 @pytest.mark.parametrize("bool_value", (True, False))
506 def test_templated_bool(self, bool_value):
507 assert (
508 html(t"<script>var x = 15; {bool_value}</script>")
509 == "<script>var x = 15; </script>"
510 )
512 def test_templated_object(self):
513 content = 0
514 assert (
515 html(t"<script>var x = {content};</script>")
516 == "<script>var x = 0;</script>"
517 )
519 @pytest.mark.parametrize(
520 "html_dunder_cls",
521 (
522 LiteralHTML,
523 Markup,
524 ),
525 )
526 def test_templated_has_html_dunder(self, html_dunder_cls):
527 content = html_dunder_cls("anything")
528 with pytest.raises(TextProcessingError, match="not supported"):
529 _ = html(t"<script>var x = 1;{content}</script>")
531 def test_templated_escaping(self):
532 content = "</script>"
533 script_t = t"<script>var x = '{content}';</script>"
534 bad_output = script_t.strings[0] + content + script_t.strings[1]
535 assert html(script_t) == "<script>var x = '\\x3c/script>';</script>"
536 assert html(script_t) != bad_output, "Sanity check."
538 def test_templated_multiple_interpolations(self):
539 assert (
540 html(t"<script>var x = {1}; var y = {2};</script>")
541 == "<script>var x = 1; var y = 2;</script>"
542 )
544 def test_not_supported_recursive_template_error(self):
545 text_t = t"script"
546 with pytest.raises(TextProcessingError, match="not supported"):
547 _ = html(t"<script>{text_t}</script>")
549 def test_not_supported_recursive_iterable_error(self):
550 texts = ["This", "is", "a", "script"]
551 with pytest.raises(TextProcessingError, match="not supported"):
552 _ = html(t"<script>{texts}</script>")
555class TestRawTextStyleDynamic:
556 def test_singleton_none(self):
557 assert html(t"<style>{None}</style>") == "<style></style>"
559 def test_singleton_str(self):
560 content = "div { background-color: red; }"
561 assert (
562 html(t"<style>{content}</style>")
563 == "<style>div { background-color: red; }</style>"
564 )
566 @pytest.mark.parametrize("bool_value", (True, False))
567 def test_singleton_bool(self, bool_value):
568 assert html(t"<style>{bool_value}</style>") == "<style></style>"
570 def test_singleton_object(self):
571 content = 0
572 assert html(t"<style>{content}</style>") == "<style>0</style>"
574 @pytest.mark.parametrize(
575 "html_dunder_cls",
576 (
577 LiteralHTML,
578 Markup,
579 ),
580 )
581 def test_singleton_has_html_dunder_pitfall(self, html_dunder_cls):
582 # @TODO: We should probably put some double override to prevent this by accident.
583 # Or just disable this and if people want to do this then put the
584 # content in a STYLE and inject the whole thing with a __html__?
585 content = html_dunder_cls("</style>")
586 assert html(t"<style>{content}</style>") == "<style></style></style>", (
587 "DO NOT DO THIS! This is just an advanced escape hatch!"
588 )
590 def test_singleton_escaping(self):
591 content = "</style>"
592 style_t = t"<style>{content}</style>"
593 bad_output = style_t.strings[0] + content + style_t.strings[1]
594 assert html(style_t) == "<style></style></style>"
595 assert html(style_t) != bad_output, "Sanity check."
597 def test_templated_none(self):
598 assert (
599 html(t"<style>h1 { background-color: red; } {None}</style>")
600 == "<style>h1 { background-color: red; }</style>"
601 )
603 def test_templated_str(self):
604 content = " h2 { background-color: blue; }"
605 assert (
606 html(t"<style>h1 { background-color: red; } {content}</style>")
607 == "<style>h1 { background-color: red; } h2 { background-color: blue; }</style>"
608 )
610 @pytest.mark.parametrize("bool_value", (True, False))
611 def test_templated_bool(self, bool_value):
612 assert (
613 html(t"<style>h1 { background-color: red; } ;{bool_value}</style>")
614 == "<style>h1 { background-color: red; };</style>"
615 )
617 def test_templated_object(self):
618 padding_right = 0
619 assert (
620 html(t"<style>h1 { padding-right: {padding_right}px; } </style>")
621 == "<style>h1 { padding-right: 0px; }</style>"
622 )
624 @pytest.mark.parametrize(
625 "html_dunder_cls",
626 (
627 LiteralHTML,
628 Markup,
629 ),
630 )
631 def test_templated_has_html_dunder(self, html_dunder_cls):
632 content = html_dunder_cls("anything")
633 with pytest.raises(TextProcessingError, match="not supported"):
634 _ = html(t"<style>h1 { color: red; } ;{content}</style>")
636 def test_templated_escaping(self):
637 content = "</style>"
638 style_t = t"<style>div { background-color: red; } {content}</style>"
639 bad_output = style_t.strings[0] + content + style_t.strings[1]
640 assert (
641 html(style_t) == "<style>div { background-color: red; } </style></style>"
642 )
643 assert html(style_t) != bad_output, "Sanity check."
645 def test_templated_multiple_interpolations(self):
646 assert (
647 html(
648 t"<style>h1 { background-color: {'red'}; } h2 { background-color: {'blue'}; } </style>"
649 )
650 == "<style>h1 { background-color: red; } h2 { background-color: blue; }</style>"
651 )
653 def test_exact_not_supported_recursive_template_error(self):
654 text_t = t"style"
655 with pytest.raises(TextProcessingError, match="not supported"):
656 _ = html(t"<style>{text_t}</style>")
658 def test_inexact_not_supported_recursive_template_error(self):
659 text_t = t"style"
660 with pytest.raises(TextProcessingError, match="not supported"):
661 _ = html(t"<style>{text_t} and more</style>")
663 def test_exact_not_supported_recursive_iterable_error(self):
664 texts = ["This", "is", "a", "style"]
665 with pytest.raises(TextProcessingError, match="not supported"):
666 _ = html(t"<style>{texts}</style>")
668 def test_inexact_not_supported_recursive_iterable_error(self):
669 texts = ["This", "is", "a", "style"]
670 with pytest.raises(TextProcessingError, match="not supported"):
671 _ = html(t"<style>{texts} and more</style>")
674class TestEscapableRawTextTitleDynamic:
675 def test_singleton_none(self):
676 assert html(t"<title>{None}</title>") == "<title></title>"
678 def test_singleton_str(self):
679 content = "Welcome To TDOM"
680 assert html(t"<title>{content}</title>") == "<title>Welcome To TDOM</title>"
682 @pytest.mark.parametrize("bool_value", (True, False))
683 def test_singleton_bool(self, bool_value):
684 assert html(t"<title>{bool_value}</title>") == "<title></title>"
686 def test_singleton_object(self):
687 content = 0
688 assert html(t"<title>{content}</title>") == "<title>0</title>"
690 @pytest.mark.parametrize(
691 "html_dunder_cls",
692 (
693 LiteralHTML,
694 Markup,
695 ),
696 )
697 def test_singleton_has_html_dunder_pitfall(self, html_dunder_cls):
698 # @TODO: We should probably put some double override to prevent this by accident.
699 content = html_dunder_cls("</title>")
700 assert html(t"<title>{content}</title>") == "<title></title></title>", (
701 "DO NOT DO THIS! This is just an advanced escape hatch!"
702 )
704 def test_singleton_escaping(self):
705 content = "</title>"
706 assert html(t"<title>{content}</title>") == "<title></title></title>"
708 def test_templated_none(self):
709 assert (
710 html(t"<title>A great story about: {None}</title>")
711 == "<title>A great story about: </title>"
712 )
714 def test_templated_str(self):
715 content = "TDOM"
716 assert (
717 html(t"<title>A great story about: {content}</title>")
718 == "<title>A great story about: TDOM</title>"
719 )
721 @pytest.mark.parametrize("bool_value", (True, False))
722 def test_templated_bool(self, bool_value):
723 assert (
724 html(t"<title>A great story; {bool_value}</title>")
725 == "<title>A great story; </title>"
726 )
728 def test_templated_object(self):
729 content = 0
730 assert (
731 html(t"<title>A great number: {content}</title>")
732 == "<title>A great number: 0</title>"
733 )
735 @pytest.mark.parametrize(
736 "html_dunder_cls",
737 (
738 LiteralHTML,
739 Markup,
740 ),
741 )
742 def test_templated_has_html_dunder(self, html_dunder_cls):
743 content = html_dunder_cls("No")
744 with pytest.raises(TextProcessingError, match="not supported"):
745 _ = html(t"<title>Literal html?: {content}</title>")
747 def test_templated_escaping(self):
748 content = "</title>"
749 assert (
750 html(t"<title>The end tag: {content}.</title>")
751 == "<title>The end tag: </title>.</title>"
752 )
754 def test_templated_multiple_interpolations(self):
755 assert (
756 html(t"<title>The number {0} is less than {1}.</title>")
757 == "<title>The number 0 is less than 1.</title>"
758 )
760 def test_exact_not_supported_recursive_template_error(self):
761 text_t = t"title"
762 with pytest.raises(TextProcessingError, match="not supported"):
763 _ = html(t"<title>{text_t}</title>")
765 def test_exact_not_supported_recursive_iterable_error(self):
766 texts = ["This", "is", "a", "title"]
767 with pytest.raises(TextProcessingError, match="not supported"):
768 _ = html(t"<title>{texts}</title>")
770 def test_inexact_not_supported_recursive_template_error(self):
771 text_t = t"title"
772 with pytest.raises(TextProcessingError, match="not supported"):
773 _ = html(t"<title>{text_t} and more</title>")
775 def test_inexact_not_supported_recursive_iterable_error(self):
776 texts = ["This", "is", "a", "title"]
777 with pytest.raises(TextProcessingError, match="not supported"):
778 _ = html(t"<title>{texts} and more</title>")
781class TestEscapableRawTextTextareaDynamic:
782 def test_singleton_none(self):
783 assert html(t"<textarea>{None}</textarea>") == "<textarea></textarea>"
785 def test_singleton_str(self):
786 content = "Welcome To TDOM"
787 assert (
788 html(t"<textarea>{content}</textarea>")
789 == "<textarea>Welcome To TDOM</textarea>"
790 )
792 @pytest.mark.parametrize("bool_value", (True, False))
793 def test_singleton_bool(self, bool_value):
794 assert html(t"<textarea>{bool_value}</textarea>") == "<textarea></textarea>"
796 def test_singleton_object(self):
797 content = 0
798 assert html(t"<textarea>{content}</textarea>") == "<textarea>0</textarea>"
800 @pytest.mark.parametrize(
801 "html_dunder_cls",
802 (
803 LiteralHTML,
804 Markup,
805 ),
806 )
807 def test_singleton_has_html_dunder_pitfall(self, html_dunder_cls):
808 # @TODO: We should probably put some double override to prevent this by accident.
809 content = html_dunder_cls("</textarea>")
810 assert (
811 html(t"<textarea>{content}</textarea>")
812 == "<textarea></textarea></textarea>"
813 ), "DO NOT DO THIS! This is just an advanced escape hatch!"
815 def test_singleton_escaping(self):
816 content = "</textarea>"
817 assert (
818 html(t"<textarea>{content}</textarea>")
819 == "<textarea></textarea></textarea>"
820 )
822 def test_templated_none(self):
823 assert (
824 html(t"<textarea>A great story about: {None}</textarea>")
825 == "<textarea>A great story about: </textarea>"
826 )
828 def test_templated_str(self):
829 content = "TDOM"
830 assert (
831 html(t"<textarea>A great story about: {content}</textarea>")
832 == "<textarea>A great story about: TDOM</textarea>"
833 )
835 @pytest.mark.parametrize("bool_value", (True, False))
836 def test_templated_bool(self, bool_value):
837 assert (
838 html(t"<textarea>This is great.{bool_value}</textarea>")
839 == "<textarea>This is great.</textarea>"
840 )
842 def test_templated_object(self):
843 content = 0
844 assert (
845 html(t"<textarea>A great number: {content}</textarea>")
846 == "<textarea>A great number: 0</textarea>"
847 )
849 @pytest.mark.parametrize(
850 "html_dunder_cls",
851 (
852 LiteralHTML,
853 Markup,
854 ),
855 )
856 def test_templated_has_html_dunder(self, html_dunder_cls):
857 content = html_dunder_cls("No")
858 with pytest.raises(TextProcessingError, match="not supported"):
859 _ = html(t"<textarea>Literal html?: {content}</textarea>")
861 def test_templated_multiple_interpolations(self):
862 assert (
863 html(t"<textarea>The number {0} is less than {1}.</textarea>")
864 == "<textarea>The number 0 is less than 1.</textarea>"
865 )
867 def test_templated_escaping(self):
868 content = "</textarea>"
869 assert (
870 html(t"<textarea>The end tag: {content}.</textarea>")
871 == "<textarea>The end tag: </textarea>.</textarea>"
872 )
874 def test_not_supported_recursive_template_error(self):
875 text_t = t"textarea"
876 with pytest.raises(TextProcessingError, match="not supported"):
877 _ = html(t"<textarea>{text_t}</textarea>")
879 def test_not_supported_recursive_iterable_error(self):
880 texts = ["This", "is", "a", "textarea"]
881 with pytest.raises(TextProcessingError, match="not supported"):
882 _ = html(t"<textarea>{texts}</textarea>")
885class Convertible:
886 def __str__(self):
887 return "string"
889 def __repr__(self):
890 return "repr"
893def test_convertible_fixture():
894 """Make sure test fixture is working correctly."""
895 c = Convertible()
896 assert f"{c!s}" == "string"
897 assert f"{c!r}" == "repr"
900def wrap_template_in_tags(
901 start_tag: str, template: Template, end_tag: str | None = None
902):
903 """Utility for testing templated text but with different containing tags."""
904 if end_tag is None:
905 end_tag = start_tag
906 return Template(f"<{start_tag}>") + template + Template(f"</{end_tag}>")
909def wrap_text_in_tags(start_tag: str, content: str, end_tag: str | None = None):
910 """Utility for testing expected text but with different containing tags."""
911 if end_tag is None:
912 end_tag = start_tag
913 # Stringify to flatten `Markup()`
914 content = str(content)
915 return f"<{start_tag}>" + content + f"</{end_tag}>"
918class TestInterpolationConversion:
919 def test_str(self):
920 c = Convertible()
921 for tag in ("p", "script", "title"):
922 assert html(wrap_template_in_tags(tag, t"{c!s}")) == wrap_text_in_tags(
923 tag, "string"
924 )
926 def test_repr(self):
927 c = Convertible()
928 for tag in ("p", "script", "title"):
929 assert html(wrap_template_in_tags(tag, t"{c!r}")) == wrap_text_in_tags(
930 tag, "repr"
931 )
933 def test_ascii_raw_text(self):
934 # single quotes are not escaped in raw text
935 assert html(wrap_template_in_tags("script", t"{'😊'!a}")) == wrap_text_in_tags(
936 "script", ascii("😊")
937 )
939 def test_ascii_escapable_normal_and_raw(self):
940 # single quotes are escaped
941 for tag in ("p", "title"):
942 assert html(wrap_template_in_tags(tag, t"{'😊'!a}")) == wrap_text_in_tags(
943 tag, escape_html_text(ascii("😊"))
944 )
947class TestInterpolationFormatSpec:
948 def test_normal_text_safe(self):
949 raw_content = "<u>underlined</u>"
950 assert (
951 html(t"<p>This is {raw_content:safe} text.</p>")
952 == "<p>This is <u>underlined</u> text.</p>"
953 )
955 def test_raw_text_safe(self):
956 # @TODO: What should even happen here?
957 raw_content = "</script>"
958 assert (
959 html(t"<script>{raw_content:safe}</script>") == "<script></script></script>"
960 ), "DO NOT DO THIS! This is an advanced escape hatch."
962 def test_escapable_raw_text_safe(self):
963 raw_content = "<u>underlined</u>"
964 assert (
965 html(t"<textarea>{raw_content:safe}</textarea>")
966 == "<textarea><u>underlined</u></textarea>"
967 )
969 def test_normal_text_unsafe(self):
970 supposedly_safe = Markup("<i>italic</i>")
971 assert (
972 html(t"<p>This is {supposedly_safe:unsafe} text.</p>")
973 == "<p>This is <i>italic</i> text.</p>"
974 )
976 def test_raw_text_unsafe(self):
977 # @TODO: What should even happen here?
978 supposedly_safe = "</script>"
979 assert (
980 html(t"<script>{supposedly_safe:unsafe}</script>")
981 == "<script>\\x3c/script></script>"
982 )
983 assert (
984 html(t"<script>{supposedly_safe:unsafe}</script>")
985 != "<script></script></script>"
986 ) # Sanity check
988 def test_escapable_raw_text_unsafe(self):
989 supposedly_safe = Markup("<i>italic</i>")
990 assert (
991 html(t"<textarea>{supposedly_safe:unsafe}</textarea>")
992 == "<textarea><i>italic</i></textarea>"
993 )
995 def test_all_text_callback(self):
996 def get_value():
997 return "dynamic"
999 for tag in ("p", "script", "style"):
1000 assert (
1001 html(
1002 Template(f"<{tag}>")
1003 + t"The value is {get_value:callback}."
1004 + Template(f"</{tag}>")
1005 )
1006 == f"<{tag}>The value is dynamic.</{tag}>"
1007 )
1009 def test_callback_nonzero_callable_error(self):
1010 def add(a, b):
1011 return a + b
1013 assert add(1, 2) == 3, "Make sure fixture could work..."
1015 for tag in ("p", "script", "style"):
1016 with pytest.raises(
1017 TypeError,
1018 match=re.compile(".* missing 2 required positional arguments"),
1019 ):
1020 _ = html(
1021 Template(f"<{tag}>")
1022 + t"The sum is {add:callback}."
1023 + Template(f"</{tag}>")
1024 )
1026 def test_callback_internal_error(self):
1027 def raise_value_error():
1028 raise ValueError("Failed to compute count.")
1030 with pytest.raises(ValueError, match=re.escape("Failed to compute count.")):
1031 _ = html(t"<div count={raise_value_error:callback}></div>")
1034# --------------------------------------------------------------------------
1035# Conditional rendering and control flow
1036# --------------------------------------------------------------------------
1039class TestUsagePatterns:
1040 def test_conditional_rendering_with_if_else(self):
1041 is_logged_in = True
1042 user_profile = t"<span>Welcome, User!</span>"
1043 login_prompt = t"<a href='/login'>Please log in</a>"
1044 assert (
1045 html(t"<div>{user_profile if is_logged_in else login_prompt}</div>")
1046 == "<div><span>Welcome, User!</span></div>"
1047 )
1049 is_logged_in = False
1050 assert (
1051 html(t"<div>{user_profile if is_logged_in else login_prompt}</div>")
1052 == '<div><a href="/login">Please log in</a></div>'
1053 )
1056# --------------------------------------------------------------------------
1057# Attributes
1058# --------------------------------------------------------------------------
1059class TestLiteralAttribute:
1060 """Test literal (non-dynamic) attributes."""
1062 def test_literal_attrs(self):
1063 assert (
1064 html(
1065 t"<a "
1066 t" id=example_link" # no quotes required if value has no surrounding whitespace
1067 t" autofocus" # bare / boolean
1068 t' title=""' # empty attribute
1069 t' href="https://example.com" target="_blank"'
1070 t"></a>"
1071 )
1072 == '<a id="example_link" autofocus title="" href="https://example.com" target="_blank"></a>'
1073 )
1075 def test_literal_attr_escaped(self):
1076 assert (
1077 html(t'<a title="<>&'""></a>')
1078 == '<a title="<>&'""></a>'
1079 )
1082class TestInterpolatedAttribute:
1083 """Test interpolated attributes, entire value is an exact interpolation."""
1085 def test_interpolated_attr(self):
1086 url = "https://example.com/"
1087 assert html(t'<a href="{url}"></a>') == '<a href="https://example.com/"></a>'
1089 def test_interpolated_attr_escaped(self):
1090 url = 'https://example.com/?q="test"&lang=en'
1091 assert (
1092 html(t'<a href="{url}"></a>')
1093 == '<a href="https://example.com/?q="test"&lang=en"></a>'
1094 )
1096 def test_interpolated_attr_unquoted(self):
1097 id = "roquefort"
1098 assert html(t"<div id={id}></div>") == '<div id="roquefort"></div>'
1100 def test_interpolated_attr_true(self):
1101 disabled = True
1102 assert (
1103 html(t"<button disabled={disabled}></button>")
1104 == "<button disabled></button>"
1105 )
1107 def test_interpolated_attr_false(self):
1108 disabled = False
1109 assert html(t"<button disabled={disabled}></button>") == "<button></button>"
1111 def test_interpolated_attr_none(self):
1112 disabled = None
1113 assert html(t"<button disabled={disabled}></button>") == "<button></button>"
1115 def test_interpolate_attr_empty_string(self):
1116 assert html(t'<div title=""></div>') == '<div title=""></div>'
1119class TestSpreadAttribute:
1120 """Test spread attributes."""
1122 def test_spread_attr(self):
1123 attrs = {"href": "https://example.com/", "target": "_blank"}
1124 assert (
1125 html(t"<a {attrs}></a>")
1126 == '<a href="https://example.com/" target="_blank"></a>'
1127 )
1129 def test_spread_attr_none(self):
1130 attrs = None
1131 assert html(t"<a {attrs}></a>") == "<a></a>"
1133 def test_spread_attr_type_errors(self):
1134 for attrs in (0, [], (), False, True):
1135 with pytest.raises(AttributeProcessingError):
1136 _ = html(t"<a {attrs}></a>")
1139class TestTemplatedAttribute:
1140 def test_templated_attr_mixed_interpolations_start_end_and_nest(self):
1141 left, middle, right = 1, 3, 5
1142 prefix, suffix = t'<div data-range="', t'"></div>'
1143 # Check interpolations at start, middle and/or end of templated attr
1144 # or a combination of those to make sure text is not getting dropped.
1145 for left_part, middle_part, right_part in product(
1146 (t"{left}", Template(str(left))),
1147 (t"{middle}", Template(str(middle))),
1148 (t"{right}", Template(str(right))),
1149 ):
1150 test_t = (
1151 prefix + left_part + t"-" + middle_part + t"-" + right_part + suffix
1152 )
1153 assert html(test_t) == '<div data-range="1-3-5"></div>'
1155 def test_templated_attr_no_quotes(self):
1156 start = 1
1157 end = 5
1158 assert (
1159 html(t"<div data-range={start}-{end}></div>")
1160 == '<div data-range="1-5"></div>'
1161 )
1164class TestAttributeMerging:
1165 def test_attr_merge_disjoint_interpolated_attr_spread_attr(self):
1166 attrs = {"href": "https://example.com/", "id": "link1"}
1167 target = "_blank"
1168 assert (
1169 html(t"<a {attrs} target={target}></a>")
1170 == '<a href="https://example.com/" id="link1" target="_blank"></a>'
1171 )
1173 def test_attr_merge_overlapping_spread_attrs(self):
1174 attrs1 = {"href": "https://example.com/", "id": "overwrtten"}
1175 attrs2 = {"target": "_blank", "id": "link1"}
1176 assert (
1177 html(t"<a {attrs1} {attrs2}></a>")
1178 == '<a href="https://example.com/" target="_blank" id="link1"></a>'
1179 )
1181 def test_attr_merge_replace_literal_attr_str_str(self):
1182 assert (
1183 html(t'<div title="default" { {"title": "fresh"} }></div>')
1184 == '<div title="fresh"></div>'
1185 )
1187 def test_attr_merge_replace_literal_attr_str_true(self):
1188 assert (
1189 html(t'<div title="default" { {"title": True} }></div>')
1190 == "<div title></div>"
1191 )
1193 def test_attr_merge_replace_literal_attr_true_str(self):
1194 assert (
1195 html(t"<div title { {'title': 'fresh'} }></div>")
1196 == '<div title="fresh"></div>'
1197 )
1199 def test_attr_merge_remove_literal_attr_str_none(self):
1200 assert html(t'<div title="default" { {"title": None} }></div>') == "<div></div>"
1202 def test_attr_merge_remove_literal_attr_true_none(self):
1203 assert html(t"<div title { {'title': None} }></div>") == "<div></div>"
1205 def test_attr_merge_other_literal_attr_intact(self):
1206 assert (
1207 html(t'<img title="default" { {"alt": "fresh"} }>')
1208 == '<img title="default" alt="fresh" />'
1209 )
1212class TestSpecialDataAttribute:
1213 """Special data attribute handling."""
1215 def test_interpolated_data_attributes(self):
1216 data = {
1217 "user-id": 123,
1218 "role": "admin",
1219 "wild": True,
1220 "false": False,
1221 "none": None,
1222 }
1223 assert (
1224 html(t"<div data={data}>User Info</div>")
1225 == '<div data-user-id="123" data-role="admin" data-wild>User Info</div>'
1226 )
1228 def test_data_attr_toggle_to_str(self):
1229 for res in [
1230 html(t"<div data-selected data={ {'selected': 'yes'} }></div>"),
1231 html(t'<div data-selected="no" data={ {"selected": "yes"} }></div>'),
1232 ]:
1233 assert res == '<div data-selected="yes"></div>'
1235 def test_data_attr_toggle_to_true(self):
1236 res = html(t'<div data-selected="yes" data={ {"selected": True} }></div>')
1237 assert res == "<div data-selected></div>"
1239 def test_data_attr_unrelated_unaffected(self):
1240 res = html(t"<div data-selected data={ {'active': True} }></div>")
1241 assert res == "<div data-selected data-active></div>"
1243 def test_data_attr_templated_error(self):
1244 data1 = {"user-id": "user-123"}
1245 data2 = {"role": "admin"}
1246 with pytest.raises(AttributeProcessingError):
1247 _ = html(t'<div data="{data1} {data2}"></div>')
1249 def test_data_attr_none(self):
1250 button_data = None
1251 res = html(t"<button data={button_data}>X</button>")
1252 assert res == "<button>X</button>"
1254 def test_data_attr_errors(self):
1255 for v in [False, [], (), 0, "data?"]:
1256 with pytest.raises(AttributeProcessingError):
1257 _ = html(t"<button data={v}>X</button>")
1259 def test_data_literal_attr_bypass(self):
1260 # Trigger overall attribute resolution with an unrelated interpolated attr.
1261 res = html(t'<p data="passthru" id={"resolved"}></p>')
1262 assert res == '<p data="passthru" id="resolved"></p>', (
1263 "A single literal attribute should not trigger data expansion."
1264 )
1267class TestSpecialAriaAttribute:
1268 """Special aria attribute handling."""
1270 def test_aria_templated_attr_error(self):
1271 aria1 = {"label": "close"}
1272 aria2 = {"hidden": "true"}
1273 with pytest.raises(AttributeProcessingError):
1274 _ = html(t'<div aria="{aria1} {aria2}"></div>')
1276 def test_interpolated_mapping(self):
1277 aria_dict = {"label": "Close", "hidden": True, "another": False, "more": None}
1278 for aria_mapping in (
1279 aria_dict,
1280 UserDict(aria_dict.items()),
1281 ): # dict and non-dict Mapping
1282 res = html(t"<button aria={aria_mapping}>X</button>")
1283 assert (
1284 res
1285 == '<button aria-label="Close" aria-hidden="true" aria-another="false">X</button>'
1286 )
1288 def test_aria_interpolate_attr_none(self):
1289 button_aria = None
1290 res = html(t"<button aria={button_aria}>X</button>")
1291 assert res == "<button>X</button>"
1293 def test_aria_attr_errors(self):
1294 for v in [False, [], (), 0, "aria?"]:
1295 with pytest.raises(AttributeProcessingError):
1296 _ = html(t"<button aria={v}>X</button>")
1298 def test_aria_literal_attr_bypass(self):
1299 # Trigger overall attribute resolution with an unrelated interpolated attr.
1300 res = html(t'<p aria="passthru" id={"resolved"}></p>')
1301 assert res == '<p aria="passthru" id="resolved"></p>', (
1302 "A single literal attribute should not trigger aria expansion."
1303 )
1306class TestSpecialClassAttribute:
1307 """Special class attribute handling."""
1309 def test_interpolated_class_attribute(self):
1310 class_list = ["btn", "btn-primary", "one two", None]
1311 class_dict = {"active": True, "btn-secondary": False}
1312 class_str = "blue"
1313 class_space_sep_str = "green yellow"
1314 class_none = None
1315 class_empty_list = []
1316 class_empty_dict = {}
1317 button_t = (
1318 t"<button "
1319 t' class="red" class={class_list} class={class_dict}'
1320 t" class={class_empty_list} class={class_empty_dict}" # ignored
1321 t" class={class_none}" # ignored
1322 t" class={class_str} class={class_space_sep_str}"
1323 t" >Click me</button>"
1324 )
1325 res = html(button_t)
1326 assert (
1327 res
1328 == '<button class="red btn btn-primary one two active blue green yellow">Click me</button>'
1329 )
1331 def test_interpolated_mapping(self):
1332 class_dict = {"active": True, "btn-secondary": False}
1333 for class_mapping in (
1334 class_dict,
1335 UserDict(class_dict.items()),
1336 ): # dict and non-dict Mapping
1337 res = html(
1338 t"<button class='btn-secondary' class={class_mapping}>X</button>"
1339 )
1340 assert res == '<button class="active">X</button>'
1342 def test_interpolated_class_attribute_with_multiple_placeholders(self):
1343 classes1 = ["btn", "btn-primary"]
1344 classes2 = [None, {"active": True}]
1345 res = html(t'<button class="{classes1} {classes2}">Click me</button>')
1346 # CONSIDER: Is this what we want? Currently, when we have multiple
1347 # placeholders in a single attribute, we treat it as a string attribute.
1348 assert (
1349 res
1350 == f'<button class="{escape_html_text(str(classes1))} {escape_html_text(str(classes2))}">Click me</button>'
1351 ), (
1352 "Interpolations that are not exact, or singletons, are instead interpreted as templates and therefore these dictionaries are strified."
1353 )
1355 def test_interpolated_attribute_spread_with_class_attribute(self):
1356 attrs = {"id": "button1", "class": ["btn", "btn-primary"]}
1357 res = html(t"<button {attrs}>Click me</button>")
1358 assert res == '<button id="button1" class="btn btn-primary">Click me</button>'
1360 def test_class_literal_attr_bypass(self):
1361 # Trigger overall attribute resolution with an unrelated interpolated attr.
1362 res = html(t'<p class="red red" id={"veryred"}></p>')
1363 assert res == '<p class="red red" id="veryred"></p>', (
1364 "A single literal attribute should not trigger class accumulator."
1365 )
1367 def test_class_none_ignored(self):
1368 class_item = None
1369 res = html(t"<p class={class_item}></p>")
1370 assert res == "<p></p>"
1371 # Also ignored inside a sequence.
1372 res = html(t"<p class={[class_item]}></p>")
1373 assert res == "<p></p>"
1375 def test_class_type_errors(self):
1376 for class_item in (False, True, 0):
1377 with pytest.raises(AttributeProcessingError):
1378 _ = html(t"<p class={class_item}></p>")
1379 with pytest.raises(AttributeProcessingError):
1380 _ = html(t"<p class={[class_item]}></p>")
1382 def test_class_merge_literals(self):
1383 res = html(t'<p class="red" class="blue"></p>')
1384 assert res == '<p class="red blue"></p>'
1386 def test_class_merge_literal_then_interpolation(self):
1387 class_item = "blue"
1388 res = html(t'<p class="red" class="{[class_item]}"></p>')
1389 assert res == '<p class="red blue"></p>'
1392class TestSpecialStyleAttribute:
1393 """Special style attribute handling."""
1395 def test_style_literal_attr_passthru(self):
1396 p_id = "para1" # non-literal attribute to cause attr resolution
1397 res = html(t'<p style="color: red" id={p_id}>Warning!</p>')
1398 assert res == '<p style="color: red" id="para1">Warning!</p>'
1400 def test_style_in_interpolated_attr(self):
1401 styles = {"color": "red", "font-weight": "bold", "font-size": "16px"}
1402 res = html(t"<p style={styles}>Warning!</p>")
1403 assert (
1404 res
1405 == '<p style="color: red; font-weight: bold; font-size: 16px">Warning!</p>'
1406 )
1408 def test_style_in_templated_attr(self):
1409 color = "red"
1410 res = html(t'<p style="color: {color}">Warning!</p>')
1411 assert res == '<p style="color: red">Warning!</p>'
1413 def test_style_in_spread_attr(self):
1414 attrs = {"style": {"color": "red"}}
1415 res = html(t"<p {attrs}>Warning!</p>")
1416 assert res == '<p style="color: red">Warning!</p>'
1418 def test_style_merged_from_all_attrs(self):
1419 attrs = {"style": "font-size: 15px"}
1420 style = {"font-weight": "bold"}
1421 color = "red"
1422 res = html(
1423 t'<p style="font-family: serif" style="color: {color}" style={style} {attrs}></p>'
1424 )
1425 assert (
1426 res
1427 == '<p style="font-family: serif; color: red; font-weight: bold; font-size: 15px"></p>'
1428 )
1430 def test_style_override_left_to_right(self):
1431 suffix = t"></p>"
1432 parts = [
1433 (t'<p style="color: red"', "color: red"),
1434 (t" style={ {'color': 'blue'} }", "color: blue"),
1435 (t' style="color: {"green"}"', "color: green"),
1436 (t""" { {"style": {"color": "yellow"}} }""", "color: yellow"),
1437 ]
1438 for index in range(len(parts)):
1439 expected_style = parts[index][1]
1440 t = sum((part[0] for part in parts[: index + 1]), t"") + suffix
1441 res = html(t)
1442 assert res == f'<p style="{expected_style}"></p>'
1444 def test_interpolated_style_attribute_multiple_placeholders(self):
1445 styles1 = {"color": "red"}
1446 styles2 = {"font-weight": "bold"}
1447 # CONSIDER: Is this what we want? Currently, when we have multiple
1448 # placeholders in a single attribute, we treat it as a string attribute
1449 # which produces an invalid style attribute.
1450 with pytest.raises(AttributeProcessingError):
1451 _ = html(t"<p style='{styles1} {styles2}'>Warning!</p>")
1453 def test_interpolated_style_attribute_merged(self):
1454 styles1 = {"color": "red"}
1455 styles2 = {"font-weight": "bold"}
1456 res = html(t"<p style={styles1} style={styles2}>Warning!</p>")
1457 assert res == '<p style="color: red; font-weight: bold">Warning!</p>'
1459 def test_interpolated_style_attribute_merged_override(self):
1460 styles1 = {"color": "red", "font-weight": "normal"}
1461 styles2 = {"font-weight": "bold"}
1462 res = html(t"<p style={styles1} style={styles2}>Warning!</p>")
1463 assert res == '<p style="color: red; font-weight: bold">Warning!</p>'
1465 def test_style_attribute_str(self):
1466 styles = "color: red; font-weight: bold;"
1467 res = html(t"<p style={styles}>Warning!</p>")
1468 assert res == '<p style="color: red; font-weight: bold">Warning!</p>'
1470 def test_style_attribute_non_str_non_dict(self):
1471 styles = [1, 2]
1472 with pytest.raises(AttributeProcessingError):
1473 _ = html(t"<p style={styles}>Warning!</p>")
1475 def test_style_literal_attr_bypass(self):
1476 # Trigger overall attribute resolution with an unrelated interpolated attr.
1477 res = html(t'<p style="invalid;invalid:" id={"resolved"}></p>')
1478 assert res == '<p style="invalid;invalid:" id="resolved"></p>', (
1479 "A single literal attribute should bypass style accumulator."
1480 )
1482 def test_style_none(self):
1483 styles = None
1484 res = html(t"<p style={styles}></p>")
1485 assert res == "<p></p>"
1488class TestSpecialAttrMerging:
1489 """
1490 Attributes should be merged left to right and displayed at the last
1491 location they were updated.
1492 """
1494 def test_accumulator_order(self):
1495 # Accumlated attrs are flattened to a value at the end of the attribute
1496 # resolution process which caused them to jump but this asserts that fix.
1497 attrs = {
1498 "class": {"btn": True, "active": True}, # Accumulated
1499 "id": "act_now", # static
1500 "data": {"wow": "such-attr"}, # Expanded
1501 "title": "mega", # static
1502 }
1503 button = html(t"<button {attrs}>Click me</button>")
1504 assert (
1505 button
1506 == '<button class="btn active" id="act_now" data-wow="such-attr" title="mega">Click me</button>'
1507 )
1510class TestPrepComponentKwargs:
1511 def test_named(self):
1512 def InputElement(size=10, type="text"):
1513 pass
1515 callable_info = get_callable_info(InputElement)
1516 assert prep_component_kwargs(callable_info, {"size": 20}, children=t"") == {
1517 "size": 20
1518 }
1519 assert prep_component_kwargs(
1520 callable_info, {"type": "email"}, children=t""
1521 ) == {"type": "email"}
1522 assert prep_component_kwargs(callable_info, {}, children=t"") == {}
1524 def test_unused_kwargs(self):
1525 def InputElement(size=10, type="text"):
1526 pass
1528 callable_info = get_callable_info(InputElement)
1529 with pytest.raises(ComponentProcessingError):
1530 assert (
1531 prep_component_kwargs(callable_info, {"type2": 15}, children=t"") == {}
1532 )
1534 def test_accepts_children(self):
1535 def DivWrapper(
1536 children: Template, add_classes: list[str] | None = None
1537 ) -> Template:
1538 return t"<div class={add_classes}>{children}</div>"
1540 callable_info = get_callable_info(DivWrapper)
1541 kwargs = prep_component_kwargs(callable_info, {}, children=t"")
1542 assert tuple(kwargs.keys()) == ("children",)
1543 assert isinstance(kwargs["children"], Template) and kwargs[
1544 "children"
1545 ].strings == ("",)
1547 add_classes = ["red"]
1548 kwargs = prep_component_kwargs(
1549 callable_info, {"add_classes": add_classes}, children=t"<span></span>"
1550 )
1551 assert set(kwargs.keys()) == {"children", "add_classes"}
1552 assert isinstance(kwargs["children"], Template) and kwargs[
1553 "children"
1554 ].strings == ("<span></span>",)
1555 assert kwargs["add_classes"] == add_classes
1557 def test_no_children(self):
1558 def SpanMaker(content_text: str) -> Template:
1559 return t"<span>{content_text}</span>"
1561 callable_info = get_callable_info(SpanMaker)
1562 content_text = "inner"
1563 kwargs = prep_component_kwargs(
1564 callable_info, {"content_text": content_text}, children=t"<div></div>"
1565 )
1566 assert kwargs == {"content_text": content_text} # no children
1568 def test_children_attr_error(self):
1569 def Comp(children: Template) -> Template:
1570 return t"<div>{children}</div>"
1572 callable_info = get_callable_info(Comp)
1573 with pytest.raises(
1574 ComponentProcessingError, match="The children attribute is reserved"
1575 ):
1576 _ = prep_component_kwargs(
1577 callable_info, {"children": t""}, children=t"<span></span>"
1578 )
1580 def test_to_snake(self):
1581 def Wrapper(mw_em, **kwargs):
1582 pass
1584 callable_info = get_callable_info(Wrapper)
1585 assert prep_component_kwargs(callable_info, {"mw-em": 20}, children=t"") == {
1586 "mw_em": 20
1587 }
1589 def test_to_snake_pass_through(self):
1590 def Wrapper(mw_em, **kwargs):
1591 pass
1593 callable_info = get_callable_info(Wrapper)
1594 assert prep_component_kwargs(
1595 callable_info,
1596 {"mw-em": 20, "hx-on:click": "alert('Clicked!')"},
1597 children=t"",
1598 ) == {
1599 "mw_em": 20, # mangled, passed as named param
1600 "hx-on:click": "alert('Clicked!')", # not mangled, will go in kwargs
1601 }
1603 @pytest.mark.parametrize(
1604 "attrs",
1605 [
1606 (
1607 ("prefix_attr_value", 10),
1608 ("prefix_attr-value", 20),
1609 ), # exact and not exact match
1610 (
1611 ("prefix-attr_value", 10),
1612 ("prefix_attr-value", 20),
1613 ), # both not exact match
1614 ],
1615 )
1616 def test_to_snake_ambiguous_collision(self, attrs):
1617 def Wrapper(prefix_attr_value, **kwargs):
1618 pass
1620 callable_info = get_callable_info(Wrapper)
1621 with pytest.raises(ComponentProcessingError, match="Ambiguous attribute "):
1622 _ = prep_component_kwargs(
1623 callable_info,
1624 dict(attrs),
1625 children=t"",
1626 )
1629class TestFunctionComponent:
1630 @staticmethod
1631 def FunctionComponent(
1632 children: Template, first: str, second: int, third_arg: str, **attrs: t.Any
1633 ) -> Template:
1634 # Ensure type correctness of props at runtime for testing purposes
1635 assert isinstance(first, str)
1636 assert isinstance(second, int)
1637 assert isinstance(third_arg, str)
1638 new_attrs = {
1639 "id": third_arg,
1640 "data": {"first": first, "second": second},
1641 **attrs,
1642 }
1643 return t"<div {new_attrs}>Component: {children}</div>"
1645 def test_with_children(self):
1646 res = html(
1647 t'<{self.FunctionComponent} first=1 second={99} third-arg="comp1" class="my-comp">Hello, Component!</{self.FunctionComponent}>'
1648 )
1649 assert (
1650 res
1651 == '<div id="comp1" data-first="1" data-second="99" class="my-comp">Component: Hello, Component!</div>'
1652 )
1654 def test_with_no_children(self):
1655 """Same test, but the caller didn't provide any children."""
1656 res = html(
1657 t'<{self.FunctionComponent} first=1 second={99} third-arg="comp1" class="my-comp" />'
1658 )
1659 assert (
1660 res
1661 == '<div id="comp1" data-first="1" data-second="99" class="my-comp">Component: </div>'
1662 )
1664 def test_missing_props_error(self):
1665 with pytest.raises(ComponentProcessingError):
1666 _ = html(
1667 t"<{self.FunctionComponent}>Missing props</{self.FunctionComponent}>"
1668 )
1671class TestFunctionComponentNoChildren:
1672 @staticmethod
1673 def FunctionComponentNoChildren(
1674 first: str, second: int, third_arg: str
1675 ) -> Template:
1676 # Ensure type correctness of props at runtime for testing purposes
1677 assert isinstance(first, str)
1678 assert isinstance(second, int)
1679 assert isinstance(third_arg, str)
1680 new_attrs = {
1681 "id": third_arg,
1682 "data": {"first": first, "second": second},
1683 }
1684 return t"<div {new_attrs}>Component: ignore children</div>"
1686 def test_interpolated_template_component_ignore_children(self):
1687 res = html(
1688 t'<{self.FunctionComponentNoChildren} first=1 second={99} third-arg="comp1">Hello, Component!</{self.FunctionComponentNoChildren}>'
1689 )
1690 assert (
1691 res
1692 == '<div id="comp1" data-first="1" data-second="99">Component: ignore children</div>'
1693 )
1696class TestFunctionComponentKeywordArgs:
1697 @staticmethod
1698 def FunctionComponentKeywordArgs(first: str, **attrs: t.Any) -> Template:
1699 # Ensure type correctness of props at runtime for testing purposes
1700 assert isinstance(first, str)
1701 if "children" in attrs:
1702 raise ValueError("Children not expected in attrs.")
1703 new_attrs = {"data-first": first, **attrs}
1704 return t"<div {new_attrs}>No children in kwargs</div>"
1706 def test_children_not_passed_via_kwargs(self):
1707 res = html(
1708 t'<{self.FunctionComponentKeywordArgs} first="value" extra="info">Child content</{self.FunctionComponentKeywordArgs}>'
1709 )
1710 assert res == '<div data-first="value" extra="info">No children in kwargs</div>'
1712 def test_children_not_passed_via_kwargs_even_when_empty(self):
1713 res = html(
1714 t'<{self.FunctionComponentKeywordArgs} first="value" extra="info" />'
1715 )
1716 assert res == '<div data-first="value" extra="info">No children in kwargs</div>'
1719class TestComponentSpecialUsage:
1720 @staticmethod
1721 def ColumnsComponent() -> Template:
1722 return t"""<td>Column 1</td><td>Column 2</td>"""
1724 def test_fragment_from_component(self):
1725 # This test assumes that if a component returns a template that parses
1726 # into multiple root elements, they are treated as a fragment.
1727 res = html(t"<table><tr><{self.ColumnsComponent} /></tr></table>")
1728 assert res == "<table><tr><td>Column 1</td><td>Column 2</td></tr></table>"
1730 def test_component_passed_as_attr_value(self):
1731 def Wrapper(
1732 children: Template, sub_component: Callable, **attrs: t.Any
1733 ) -> Template:
1734 return t"<{sub_component} {attrs}>{children}</{sub_component}>"
1736 res = html(
1737 t'<{Wrapper} sub-component={TestFunctionComponent.FunctionComponent} class="wrapped" first=1 second={99} third-arg="comp1"><p>Inside wrapper</p></{Wrapper}>'
1738 )
1739 assert (
1740 res
1741 == '<div id="comp1" data-first="1" data-second="99" class="wrapped">Component: <p>Inside wrapper</p></div>'
1742 )
1744 def test_nested_component_gh23(self):
1745 # @DESIGN: Do we need this? Should we recommend an alternative?
1746 # See https://github.com/t-strings/tdom/issues/23 for context
1747 def Header() -> Template:
1748 return t"{'Hello World'}"
1750 res = html(t"<{Header} />", assume_ctx=make_ctx(parent_tag="div"))
1751 assert res == "Hello World"
1754class TestClassComponent:
1755 @dataclass
1756 class ClassComponent:
1757 """Example class-based component."""
1759 user_name: str
1760 image_url: str
1761 children: Template
1762 homepage: str = "#"
1764 def __call__(self) -> Template:
1765 return (
1766 t"<div class='avatar'>"
1767 t"<a href={self.homepage}>"
1768 t"<img src='{self.image_url}' alt='{f'Avatar of {self.user_name}'}' />"
1769 t"</a>"
1770 t"<span>{self.user_name}</span>"
1771 t"{self.children}"
1772 t"</div>"
1773 )
1775 def test_class_component_implicit_invocation_with_children(self):
1776 res = html(
1777 t"<{self.ClassComponent} user-name='Alice' image-url='https://example.com/alice.png'>Fun times!</{self.ClassComponent}>"
1778 )
1779 assert (
1780 res
1781 == '<div class="avatar"><a href="#"><img src="https://example.com/alice.png" alt="Avatar of Alice" /></a><span>Alice</span>Fun times!</div>'
1782 )
1784 def test_class_component_direct_invocation(self):
1785 avatar = self.ClassComponent(
1786 user_name="Alice",
1787 image_url="https://example.com/alice.png",
1788 homepage="https://example.com/users/alice",
1789 children=t"", # Children is required so we set it to an empty template.
1790 )
1791 res = html(t"<{avatar} />")
1792 assert (
1793 res
1794 == '<div class="avatar"><a href="https://example.com/users/alice"><img src="https://example.com/alice.png" alt="Avatar of Alice" /></a><span>Alice</span></div>'
1795 )
1797 @dataclass
1798 class ClassComponentNoChildren:
1799 """Example class-based component that does not ask for children."""
1801 user_name: str
1802 image_url: str
1803 homepage: str = "#"
1805 def __call__(self) -> Template:
1806 return (
1807 t"<div class='avatar'>"
1808 t"<a href={self.homepage}>"
1809 t"<img src='{self.image_url}' alt='{f'Avatar of {self.user_name}'}' />"
1810 t"</a>"
1811 t"<span>{self.user_name}</span>"
1812 t"ignore children"
1813 t"</div>"
1814 )
1816 def test_implicit_invocation_ignore_children(self):
1817 res = html(
1818 t"<{self.ClassComponentNoChildren} user-name='Alice' image-url='https://example.com/alice.png'>Fun times!</{self.ClassComponentNoChildren}>"
1819 )
1820 assert (
1821 res
1822 == '<div class="avatar"><a href="#"><img src="https://example.com/alice.png" alt="Avatar of Alice" /></a><span>Alice</span>ignore children</div>'
1823 )
1826def test_attribute_type_component():
1827 def AttributeTypeComponent(
1828 data_int: int,
1829 data_true: bool,
1830 data_false: bool,
1831 data_none: None,
1832 data_float: float,
1833 data_dt: datetime.datetime,
1834 **kws: dict[str, object | None],
1835 ) -> Template:
1836 """Component to test that we don't incorrectly convert attribute types."""
1837 assert isinstance(data_int, int)
1838 assert data_true is True
1839 assert data_false is False
1840 assert data_none is None
1841 assert isinstance(data_float, float)
1842 assert isinstance(data_dt, datetime.datetime)
1843 for kw, v_type in [
1844 ("spread_true", True),
1845 ("spread_false", False),
1846 ("spread_int", int),
1847 ("spread_none", None),
1848 ("spread_float", float),
1849 ("spread_dt", datetime.datetime),
1850 ("spread_dict", dict),
1851 ("spread_list", list),
1852 ]:
1853 if v_type in (True, False, None):
1854 assert kw in kws and kws[kw] is v_type, (
1855 f"{kw} should be {v_type} but got {kws=}"
1856 )
1857 else:
1858 assert kw in kws and isinstance(kws[kw], v_type), (
1859 f"{kw} should instance of {v_type} but got {kws=}"
1860 )
1861 return t"Looks good!"
1863 an_int: int = 42
1864 a_true: bool = True
1865 a_false: bool = False
1866 a_none: None = None
1867 a_float: float = math.pi
1868 a_dt: datetime.datetime = datetime.datetime(
1869 2024, 1, 1, 12, 0, 0, tzinfo=datetime.UTC
1870 )
1871 spread_attrs: dict[str, object | None] = {
1872 "spread_true": True,
1873 "spread_false": False,
1874 "spread_none": None,
1875 "spread_int": 0,
1876 "spread_float": 0.0,
1877 "spread_dt": datetime.datetime(2024, 1, 1, 12, 0, 1, tzinfo=datetime.UTC),
1878 "spread_dict": {},
1879 "spread_list": ["eggs", "milk"],
1880 }
1881 res = html(
1882 t"<{AttributeTypeComponent} data-int={an_int} data-true={a_true} "
1883 t"data-false={a_false} data-none={a_none} data-float={a_float} "
1884 t"data-dt={a_dt} {spread_attrs}/>"
1885 )
1886 assert res == "Looks good!"
1889class TestComponentErrors:
1890 def test_component_non_callable_fails(self):
1891 with pytest.raises(ComponentProcessingError, match="must be callable"):
1892 _ = html(t"<{'not a function'} />")
1894 def test_catchall_for_attr_prep_callback_error(self):
1895 def prep_attr():
1896 return 1 / 0
1898 def Repeat(count: int = 0, children: Template = t"") -> Template:
1899 return sum([children] * count, t"")
1901 with pytest.raises(
1902 ZeroDivisionError,
1903 ):
1904 _ = html(t"<{Repeat} count={prep_attr:callback}><span>OK</span></{Repeat}>")
1906 def test_normal_attr_error(self):
1907 def Comp(children: Template, **kwargs) -> Template:
1908 return t"<div {kwargs}>{children}</div>"
1910 with pytest.raises(
1911 AttributeProcessingError, match="Cannot use int as value for aria attribute"
1912 ):
1913 _ = html(t"<{Comp} aria={0}><span>OK</span></{Comp}>")
1915 def test_component_requiring_positional_arg_fails(self):
1916 def RequiresPositional(whoops: int, /) -> Template: # pragma: no cover
1917 return t"<p>Positional arg: {whoops}</p>"
1919 with pytest.raises(
1920 ComponentProcessingError, match="cannot have required positional arguments"
1921 ):
1922 _ = html(t"<{RequiresPositional} />")
1924 def test_mismatched_component_closing_tag_fails(self):
1925 def OpenTag(children: Template) -> Template:
1926 return t"<div>open</div>"
1928 def CloseTag(children: Template) -> Template:
1929 return t"<div>close</div>"
1931 with pytest.raises(
1932 ComponentProcessingError, match="must match component callable"
1933 ):
1934 _ = html(t"<{OpenTag}>Hello</{CloseTag}>")
1936 def test_func_comp_error(self):
1937 def RaisesValueError(children: Template) -> Template:
1938 raise ValueError("Failed to build template.")
1940 with pytest.raises(
1941 ValueError,
1942 match=re.escape("Failed to build template"),
1943 ):
1944 _ = html(t"<{RaisesValueError}>Hello</{RaisesValueError}>")
1946 def test_factory_comp_error(self):
1947 def RaisesValueError(children: Template) -> Callable[[], Template]:
1948 def _RaisesValueError() -> Template:
1949 raise ValueError("Failed to build template.")
1951 return _RaisesValueError
1953 with pytest.raises(ValueError, match=re.escape("Failed to build template.")):
1954 _ = html(t"<{RaisesValueError}>Hello</{RaisesValueError}>")
1956 @pytest.mark.parametrize(
1957 "bad_value", ("", "text", None, 1, ("tuple", "of", "strs"))
1958 )
1959 def test_function_component_returns_nontemplate_fails(self, bad_value):
1960 def BadFunctionComp(children: Template):
1961 return bad_value
1963 with pytest.raises(
1964 ComponentProcessingError,
1965 match="Component callable must return Template or Callable:",
1966 ):
1967 _ = html(t"<{BadFunctionComp}>Hello</{BadFunctionComp}>")
1969 @pytest.mark.parametrize(
1970 "bad_value", ("", "text", None, 1, ("tuple", "of", "strs"))
1971 )
1972 def test_component_object_returns_nontemplate_fails(self, bad_value):
1973 def BadFactoryComp(children: Template):
1974 def component_object():
1975 return bad_value
1977 return component_object
1979 with pytest.raises(
1980 ComponentProcessingError,
1981 match="Component object must return Template when called:",
1982 ):
1983 _ = html(t"<{BadFactoryComp}>Hello</{BadFactoryComp}>")
1986def test_integration_basic():
1987 comment_text = "comment is not literal"
1988 interpolated_class = "red"
1989 text_in_element = "text is not literal"
1990 templated = "not literal"
1991 spread_attrs = {"data-on": True}
1992 markup_content = Markup("<div>safe</div>")
1994 def WrapperComponent(children):
1995 return t"<div>{children}</div>"
1997 smoke_t = t"""<!doctype html>
1998<html>
1999<body>
2000<!-- literal -->
2001<span attr="literal">literal</span>
2002<!-- {comment_text} -->
2003<span>{text_in_element}</span>
2004<span attr="literal" class={interpolated_class} title="is {templated}" {spread_attrs}>{text_in_element}</span>
2005<{WrapperComponent}><span>comp body</span></{WrapperComponent}>
2006{markup_content}
2007</body>
2008</html>"""
2009 smoke_str = """<!DOCTYPE html>
2010<html>
2011<body>
2012<!-- literal -->
2013<span attr="literal">literal</span>
2014<!-- comment is not literal -->
2015<span>text is not literal</span>
2016<span attr="literal" class="red" title="is not literal" data-on>text is not literal</span>
2017<div><span>comp body</span></div>
2018<div>safe</div>
2019</body>
2020</html>"""
2021 assert html(smoke_t) == smoke_str
2024def struct_repr(st):
2025 """Breakdown Templates into comparable parts for test verification."""
2026 return st.strings, tuple(
2027 (i.value, i.expression, i.conversion, i.format_spec) for i in st.interpolations
2028 )
2031def test_process_template_internal_cache():
2032 """Test that cache and non-cache both generally work as expected."""
2033 # @NOTE: We use a made-up custom element so that we can be sure to
2034 # miss the cache. If this element is used elsewhere than the global
2035 # cache might cache it and it will ruin our counting, specifically
2036 # the first miss will instead be a hit.
2037 sample_t = t"<div>{'content'}<tdom-cache-test-element /></div>"
2038 sample_diff_t = t"<div>{'diffcontent'}<tdom-cache-test-element /></div>"
2039 alt_t = t"<span>{'content'}</span>"
2040 process_api = TemplateProcessor(parser_api=TemplateParserProxy())
2041 cached_process_api = TemplateProcessor(parser_api=CachedTemplateParserProxy())
2042 # Because the cache is stored on the class itself this can be affect by
2043 # other tests, so save this off and take the difference to determine the result,
2044 # this is not great and hopefully we can find a better solution.
2045 assert isinstance(cached_process_api, TemplateProcessor)
2046 assert isinstance(cached_process_api.parser_api, CachedTemplateParserProxy)
2047 start_ci = cached_process_api.parser_api._to_ttree.cache_info()
2048 tnode1 = process_api.parser_api.to_ttree(sample_t).root
2049 tnode2 = process_api.parser_api.to_ttree(sample_t).root
2050 cached_tnode1 = cached_process_api.parser_api.to_ttree(sample_t).root
2051 cached_tnode2 = cached_process_api.parser_api.to_ttree(sample_t).root
2052 cached_tnode3 = cached_process_api.parser_api.to_ttree(sample_diff_t).root
2053 # Check that the uncached and cached services are actually
2054 # returning non-identical results.
2055 assert tnode1 is not cached_tnode1
2056 assert tnode1 is not cached_tnode2
2057 assert tnode1 is not cached_tnode3
2058 # Check that the uncached service returns a brand new result everytime.
2059 assert tnode1 is not tnode2
2060 # Check that the cached service is returning the exact same, identical, result.
2061 assert cached_tnode1 is cached_tnode2
2062 # Even if the input templates are not identical (but are still equivalent).
2063 assert cached_tnode1 is cached_tnode3 and sample_t is not sample_diff_t
2064 # Check that the cached service and uncached services return
2065 # results that are equivalent (even though they are not (id)entical).
2066 assert tnode1 == cached_tnode1
2067 assert tnode2 == cached_tnode1
2068 # Now that we are setup we check that the cache is internally
2069 # working as we intended.
2070 ci = cached_process_api.parser_api._to_ttree.cache_info()
2071 # cached_tnode2 and cached_tnode3 are hits after cached_tnode1
2072 assert ci.hits - start_ci.hits == 2
2073 # cached_tf1 was a miss because cache was empty (brand new)
2074 assert ci.misses - start_ci.misses == 1
2075 cached_tnode4 = cached_process_api.parser_api.to_ttree(alt_t).root
2076 # A different template produces a brand new tf.
2077 assert cached_tnode1 is not cached_tnode4
2078 # The template is new AND has a different structure so it also
2079 # produces an unequivalent tf.
2080 assert cached_tnode1 != cached_tnode4
2083def test_cached_component_span_extracts_current_interpolations():
2084 def Component(children):
2085 return children
2087 def make_template(child):
2088 return t"<{Component}><tdom-span-cache>{child}</tdom-span-cache></{Component}>"
2090 process_api = TemplateProcessor(parser_api=CachedTemplateParserProxy())
2092 assert process_api.process(make_template("first"), ProcessContext()) == (
2093 "<tdom-span-cache>first</tdom-span-cache>"
2094 )
2095 assert process_api.process(make_template("second"), ProcessContext()) == (
2096 "<tdom-span-cache>second</tdom-span-cache>"
2097 )
2100def test_repeat_calls():
2101 """Crude check for any unintended state being kept between calls."""
2103 def get_sample_t(idx, spread_attrs, button_text):
2104 return t"""<div><button data-key={idx} {spread_attrs}>{button_text}</button></div>"""
2106 for idx in range(3):
2107 spread_attrs = {"data-enabled": True}
2108 button_text = "PROCESS"
2109 sample_t = get_sample_t(idx, spread_attrs, button_text)
2110 assert (
2111 html(sample_t)
2112 == f'<div><button data-key="{idx}" data-enabled>PROCESS</button></div>'
2113 )
2116def get_select_t_with_list(options, selected_values):
2117 return t"""<select>{
2118 [
2119 t"<option value={opt[0]} selected={opt[0] in selected_values}>{opt[1]}</option>"
2120 for opt in options
2121 ]
2122 }</select>"""
2125def get_select_t_with_generator(options, selected_values):
2126 return t"""<select>{
2127 (
2128 t"<option value={opt[0]} selected={opt[0] in selected_values}>{opt[1]}</option>"
2129 for opt in options
2130 )
2131 }</select>"""
2134def get_select_t_with_concat(options, selected_values):
2135 parts = [t"<select>"]
2136 parts.extend(
2137 [
2138 t"<option value={opt[0]} selected={opt[0] in selected_values}>{opt[1]}</option>"
2139 for opt in options
2140 ]
2141 )
2142 parts.append(t"</select>")
2143 return sum(parts, t"")
2146@pytest.mark.parametrize(
2147 "provider",
2148 (
2149 get_select_t_with_list,
2150 get_select_t_with_generator,
2151 get_select_t_with_concat,
2152 ),
2153)
2154def test_process_template_iterables(provider):
2155 def get_color_select_t(selected_values: set, provider: Callable) -> Template:
2156 PRIMARY_COLORS = [("R", "Red"), ("Y", "Yellow"), ("B", "Blue")]
2157 assert set(selected_values).issubset({opt[0] for opt in PRIMARY_COLORS})
2158 return provider(PRIMARY_COLORS, selected_values)
2160 no_selection_t = get_color_select_t(set(), provider)
2161 assert (
2162 html(no_selection_t)
2163 == '<select><option value="R">Red</option><option value="Y">Yellow</option><option value="B">Blue</option></select>'
2164 )
2165 selected_yellow_t = get_color_select_t({"Y"}, provider)
2166 assert (
2167 html(selected_yellow_t)
2168 == '<select><option value="R">Red</option><option value="Y" selected>Yellow</option><option value="B">Blue</option></select>'
2169 )
2172def test_component_integration():
2173 """Broadly test that common template component usage works."""
2175 def PageComponent(children, root_attrs=None):
2176 return t"""<div class="content" {root_attrs}>{children}</div>"""
2178 def FooterComponent(classes=("footer-default",)):
2179 return t'<div class="footer" class={classes}><a href="about">About</a></div>'
2181 def LayoutComponent(children, body_classes=None):
2182 return t"""<!doctype html>
2183<html>
2184 <head>
2185 <meta charset="utf-8">
2186 <script src="scripts.js"></script>
2187 <link rel="stylesheet" href="styles.css">
2188 </head>
2189 <body class={body_classes}>
2190 {children}
2191 <{FooterComponent} />
2192 </body>
2193</html>
2194"""
2196 content = "HTML never goes out of style."
2197 content_str = html(
2198 t"<{LayoutComponent} body_classes={['theme-default']}><{PageComponent}>{content}</{PageComponent}></{LayoutComponent}>"
2199 )
2200 assert (
2201 content_str
2202 == """<!DOCTYPE html>
2203<html>
2204 <head>
2205 <meta charset="utf-8" />
2206 <script src="scripts.js"></script>
2207 <link rel="stylesheet" href="styles.css" />
2208 </head>
2209 <body class="theme-default">
2210 <div class="content">HTML never goes out of style.</div>
2211 <div class="footer footer-default"><a href="about">About</a></div>
2212 </body>
2213</html>
2214"""
2215 )
2218class TestInterpolatingHTMLInTemplateWithDynamicParentTag:
2219 """
2220 When a template does not have a parent tag we cannot determine the type
2221 of text that should be allowed and therefore we cannot determine how to
2222 escape that text. Once the type is known we should escape any
2223 interpolations in that text correctly.
2224 """
2226 def test_dynamic_raw_text(self):
2227 """Type raw text should fail because template is already not allowed."""
2228 content = '<script>console.log("123!");</script>'
2229 content_t = t"{content}"
2230 content_t = t'<script>console.log("{123}!");</script>'
2231 with pytest.raises(
2232 TextProcessingError,
2233 match="Template and Iterable interpolation values are not supported within script",
2234 ):
2235 _ = html(t"<script>{content_t}</script>")
2237 def test_dynamic_escapable_raw_text(self):
2238 """Type escapable raw text should fail because template is already not allowed."""
2239 content = '<script>console.log("123!");</script>'
2240 content_t = t"{content}"
2241 with pytest.raises(
2242 TextProcessingError,
2243 match="Template and Iterable interpolation values are not supported within textarea",
2244 ):
2245 _ = html(t"<textarea>{content_t}</textarea>")
2247 def test_dynamic_normal_text(self):
2248 """Escaping should be applied when normal text type is goes into effect."""
2249 content = '<script>console.log("123!");</script>'
2250 content_t = t"{content}"
2251 LT, GT, DQ = map(markupsafe_escape, ["<", ">", '"'])
2252 assert (
2253 html(t"<div>{content_t}</div>")
2254 == f"<div>{LT}script{GT}console.log({DQ}123!{DQ});{LT}/script{GT}</div>"
2255 )
2258class TestPagerComponentExample:
2259 @dataclass
2260 class Pager:
2261 left_pages: tuple = ()
2262 page: int = 0
2263 right_pages: tuple = ()
2264 prev_page: int | None = None
2265 next_page: int | None = None
2267 @dataclass
2268 class PagerDisplay:
2269 pager: TestPagerComponentExample.Pager
2270 paginate_url: Callable[[int], str]
2271 root_classes: tuple[str, ...] = ("cb", "tc", "w-100")
2272 part_classes: tuple[str, ...] = ("dib", "pa1")
2274 def __call__(self) -> Template:
2275 parts = [t"<div class={self.root_classes}>"]
2276 if self.pager.prev_page:
2277 parts.append(
2278 t"<a class={self.part_classes} href={self.paginate_url(self.pager.prev_page)}>Prev</a>"
2279 )
2280 for left_page in self.pager.left_pages:
2281 parts.append(
2282 t'<a class={self.part_classes} href="{self.paginate_url(left_page)}">{left_page}</a>'
2283 )
2284 parts.append(t"<span class={self.part_classes}>{self.pager.page}</span>")
2285 for right_page in self.pager.right_pages:
2286 parts.append(
2287 t'<a class={self.part_classes} href="{self.paginate_url(right_page)}">{right_page}</a>'
2288 )
2289 if self.pager.next_page:
2290 parts.append(
2291 t"<a class={self.part_classes} href={self.paginate_url(self.pager.next_page)}>Next</a>"
2292 )
2293 parts.append(t"</div>")
2294 return Template(*chain.from_iterable(parts))
2296 def test_example(self):
2297 def paginate_url(page: int) -> str:
2298 return f"/pages?page={page}"
2300 def Footer(pager, paginate_url, footer_classes=("footer",)) -> Template:
2301 return t"<div class={footer_classes}><{self.PagerDisplay} pager={pager} paginate_url={paginate_url} /></div>"
2303 pager = self.Pager(
2304 left_pages=(1, 2), page=3, right_pages=(4, 5), next_page=6, prev_page=None
2305 )
2306 content_t = t"<{Footer} pager={pager} paginate_url={paginate_url} />"
2307 res = html(content_t)
2308 print(res)
2309 assert (
2310 res
2311 == '<div class="footer"><div class="cb tc w-100"><a class="dib pa1" href="/pages?page=1">1</a><a class="dib pa1" href="/pages?page=2">2</a><span class="dib pa1">3</span><a class="dib pa1" href="/pages?page=4">4</a><a class="dib pa1" href="/pages?page=5">5</a><a class="dib pa1" href="/pages?page=6">Next</a></div></div>'
2312 )
2315def test_mathml():
2316 num = 1
2317 denom = 3
2318 mathml_t = t"""<p>
2319 The fraction
2320 <math>
2321 <mfrac>
2322 <mn>{num}</mn>
2323 <mn>{denom}</mn>
2324 </mfrac>
2325 </math>
2326 is not a decimal number.
2327</p>"""
2328 res = html(mathml_t)
2329 assert (
2330 str(res)
2331 == """<p>
2332 The fraction
2333 <math>
2334 <mfrac>
2335 <mn>1</mn>
2336 <mn>3</mn>
2337 </mfrac>
2338 </math>
2339 is not a decimal number.
2340</p>"""
2341 )
2344def test_issue_166():
2345 template = t"<button disabled={True}>x</button><button disabled={True}>y</button>"
2346 expected = "<button disabled>x</button><button disabled>y</button>"
2347 assert html(template) == expected
2350@pytest.fixture
2351def bad_html_dunder():
2352 return _BadHTMLDunder()
2355class _BadHTMLDunder:
2356 def __html__(self):
2357 raise ValueError("bad value")