Skip to content

Commit f4b37f6

Browse files
committed
Add explicit component function test
1 parent 8aefeca commit f4b37f6

File tree

2 files changed

+54
-1
lines changed

2 files changed

+54
-1
lines changed

tdom/processor_test.py

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import typing as t
2+
from dataclasses import dataclass
23
from string.templatelib import Template
34

45
import pytest
@@ -605,3 +606,55 @@ def Items() -> Node:
605606
],
606607
)
607608
assert str(node) == "<ul><li>Item 1</li><li>Item 2</li><li>Item 3</li></ul>"
609+
610+
611+
@dataclass
612+
class Avatar:
613+
"""Example class-based component."""
614+
615+
user_name: str
616+
image_url: str
617+
homepage: str = "#"
618+
619+
def __call__(self) -> Node:
620+
return html(
621+
t"<div class='avatar'>"
622+
t"<a href={self.homepage}>"
623+
t"<img src='{self.image_url}' alt='{f'Avatar of {self.user_name}'}' />"
624+
t"</a>"
625+
t"<span>{self.user_name}</span>"
626+
t"</div>"
627+
)
628+
629+
630+
def test_class_based_component():
631+
avatar = Avatar(
632+
user_name="Alice",
633+
image_url="https://example.com/alice.png",
634+
homepage="https://example.com/users/alice",
635+
)
636+
node = html(t"<{avatar} />")
637+
assert node == Element(
638+
"div",
639+
attrs={"class": "avatar"},
640+
children=[
641+
Element(
642+
"a",
643+
attrs={"href": "https://example.com/users/alice"},
644+
children=[
645+
Element(
646+
"img",
647+
attrs={
648+
"src": "https://example.com/alice.png",
649+
"alt": "Avatar of Alice",
650+
},
651+
)
652+
],
653+
),
654+
Element("span", children=[Text("Alice")]),
655+
],
656+
)
657+
assert (
658+
str(node)
659+
== '<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>'
660+
)

uv.lock

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)