1- from tdom import Element , Text , html
1+ from dataclasses import dataclass
2+ from tdom import Text , html
23from tdom .types import Context
34
45
5- def test_context_passed_to_component_simple ():
6+ def test_context_passed_to_function_component_simple ():
67 calls : list [dict [str , object ] | None ] = []
78
89 def Comp (* children : Text , answer : int , context : Context = None ):
@@ -13,7 +14,7 @@ def Comp(*children: Text, answer: int, context: Context = None):
1314 assert calls == [{"x" : 7 }]
1415
1516
16- def test_context_passed_to_subcomponent_via_template ():
17+ def test_context_passed_to_function_subcomponent_via_template ():
1718 seen : list [object ] = []
1819
1920 def Child (* children : Text , context : Context = None ):
@@ -28,7 +29,7 @@ def Parent(*children: Text, context: Context = None):
2829 assert seen == ["alice" ]
2930
3031
31- def test_context_not_required_for_component ():
32+ def test_context_not_required_for_function_component ():
3233 # Component does not accept `context`; passing context to html() should not break.
3334 def NoCtx (* children : Text , answer : int ):
3435 return Text (f"answer={ answer } " )
@@ -37,3 +38,40 @@ def NoCtx(*children: Text, answer: int):
3738 # Fake out PyCharm's type checker
3839 children = getattr (node , "children" )
3940 assert children [0 ].text == "answer=42"
41+
42+
43+ def test_context_passed_to_class_component_simple ():
44+ calls : list [dict [str , object ] | None ] = []
45+
46+ @dataclass
47+ class CompClass :
48+ answer : int
49+ context : Context = None
50+
51+ def __call__ (self ) -> Text :
52+ calls .append (self .context )
53+ return Text (
54+ f"answer={ self .answer } ,ctx={ self .context ['x' ] if self .context else 'None' } "
55+ )
56+
57+ comp = CompClass (answer = 42 , context = {"x" : 7 })
58+ html (t "<div><{comp} /></div>" )
59+
60+ # Ensure context was available on the instance
61+ assert calls == [{"x" : 7 }]
62+
63+
64+ def test_context_not_required_for_class_component ():
65+ @dataclass
66+ class NoCtxClass :
67+ answer : int
68+ context : Context = None
69+
70+ def __call__ (self ) -> Text :
71+ return Text (f"answer={ self .answer } " )
72+
73+ node = html (t "<div><{NoCtxClass(answer=42)} /></div>" , context = {"x" : 7 })
74+
75+ # Fake out PyCharm's type checker
76+ children = getattr (node , "children" )
77+ assert children [0 ].text == "answer=42"
0 commit comments