test_component.py 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217
  1. from contextlib import nullcontext
  2. from typing import Any, Dict, List, Optional, Type, Union
  3. import pytest
  4. import reflex as rx
  5. from reflex.base import Base
  6. from reflex.compiler.compiler import compile_components
  7. from reflex.components.base.bare import Bare
  8. from reflex.components.base.fragment import Fragment
  9. from reflex.components.component import (
  10. Component,
  11. CustomComponent,
  12. StatefulComponent,
  13. custom_component,
  14. )
  15. from reflex.components.radix.themes.layout.box import Box
  16. from reflex.constants import EventTriggers
  17. from reflex.event import (
  18. EventChain,
  19. EventHandler,
  20. empty_event,
  21. input_event,
  22. parse_args_spec,
  23. )
  24. from reflex.state import BaseState
  25. from reflex.style import Style
  26. from reflex.utils import imports
  27. from reflex.utils.exceptions import EventFnArgMismatch, EventHandlerArgMismatch
  28. from reflex.utils.imports import ImportDict, ImportVar, ParsedImportDict, parse_imports
  29. from reflex.vars import VarData
  30. from reflex.vars.base import LiteralVar, Var
  31. @pytest.fixture
  32. def test_state():
  33. class TestState(BaseState):
  34. num: int
  35. def do_something(self):
  36. pass
  37. def do_something_arg(self, arg):
  38. pass
  39. return TestState
  40. @pytest.fixture
  41. def component1() -> Type[Component]:
  42. """A test component.
  43. Returns:
  44. A test component.
  45. """
  46. class TestComponent1(Component):
  47. # A test string prop.
  48. text: Var[str]
  49. # A test number prop.
  50. number: Var[int]
  51. # A test string/number prop.
  52. text_or_number: Var[Union[int, str]]
  53. def _get_imports(self) -> ParsedImportDict:
  54. return {"react": [ImportVar(tag="Component")]}
  55. def _get_custom_code(self) -> str:
  56. return "console.log('component1')"
  57. return TestComponent1
  58. @pytest.fixture
  59. def component2() -> Type[Component]:
  60. """A test component.
  61. Returns:
  62. A test component.
  63. """
  64. class TestComponent2(Component):
  65. # A test list prop.
  66. arr: Var[List[str]]
  67. on_prop_event: EventHandler[lambda e0: [e0]]
  68. def get_event_triggers(self) -> Dict[str, Any]:
  69. """Test controlled triggers.
  70. Returns:
  71. Test controlled triggers.
  72. """
  73. return {
  74. **super().get_event_triggers(),
  75. "on_open": lambda e0: [e0],
  76. "on_close": lambda e0: [e0],
  77. }
  78. def _get_imports(self) -> ParsedImportDict:
  79. return {"react-redux": [ImportVar(tag="connect")]}
  80. def _get_custom_code(self) -> str:
  81. return "console.log('component2')"
  82. return TestComponent2
  83. @pytest.fixture
  84. def component3() -> Type[Component]:
  85. """A test component with hook defined.
  86. Returns:
  87. A test component.
  88. """
  89. class TestComponent3(Component):
  90. def _get_hooks(self) -> str:
  91. return "const a = () => true"
  92. return TestComponent3
  93. @pytest.fixture
  94. def component4() -> Type[Component]:
  95. """A test component with hook defined.
  96. Returns:
  97. A test component.
  98. """
  99. class TestComponent4(Component):
  100. def _get_hooks(self) -> str:
  101. return "const b = () => false"
  102. return TestComponent4
  103. @pytest.fixture
  104. def component5() -> Type[Component]:
  105. """A test component.
  106. Returns:
  107. A test component.
  108. """
  109. class TestComponent5(Component):
  110. tag = "RandomComponent"
  111. _invalid_children: List[str] = ["Text"]
  112. _valid_children: List[str] = ["Text"]
  113. _valid_parents: List[str] = ["Text"]
  114. return TestComponent5
  115. @pytest.fixture
  116. def component6() -> Type[Component]:
  117. """A test component.
  118. Returns:
  119. A test component.
  120. """
  121. class TestComponent6(Component):
  122. tag = "RandomComponent"
  123. _invalid_children: List[str] = ["Text"]
  124. return TestComponent6
  125. @pytest.fixture
  126. def component7() -> Type[Component]:
  127. """A test component.
  128. Returns:
  129. A test component.
  130. """
  131. class TestComponent7(Component):
  132. tag = "RandomComponent"
  133. _valid_children: List[str] = ["Text"]
  134. return TestComponent7
  135. @pytest.fixture
  136. def on_click1() -> EventHandler:
  137. """A sample on click function.
  138. Returns:
  139. A sample on click function.
  140. """
  141. def on_click1():
  142. pass
  143. return EventHandler(fn=on_click1)
  144. @pytest.fixture
  145. def on_click2() -> EventHandler:
  146. """A sample on click function.
  147. Returns:
  148. A sample on click function.
  149. """
  150. def on_click2():
  151. pass
  152. return EventHandler(fn=on_click2)
  153. @pytest.fixture
  154. def my_component():
  155. """A test component function.
  156. Returns:
  157. A test component function.
  158. """
  159. def my_component(prop1: Var[str], prop2: Var[int]):
  160. return Box.create(prop1, prop2)
  161. return my_component
  162. def test_set_style_attrs(component1):
  163. """Test that style attributes are set in the dict.
  164. Args:
  165. component1: A test component.
  166. """
  167. component = component1(color="white", text_align="center")
  168. assert str(component.style["color"]) == '"white"'
  169. assert str(component.style["textAlign"]) == '"center"'
  170. def test_custom_attrs(component1):
  171. """Test that custom attributes are set in the dict.
  172. Args:
  173. component1: A test component.
  174. """
  175. component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
  176. assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
  177. def test_create_component(component1):
  178. """Test that the component is created correctly.
  179. Args:
  180. component1: A test component.
  181. """
  182. children = [component1() for _ in range(3)]
  183. attrs = {"color": "white", "text_align": "center"}
  184. c = component1.create(*children, **attrs)
  185. assert isinstance(c, component1)
  186. assert c.children == children
  187. assert (
  188. str(LiteralVar.create(c.style))
  189. == '({ ["color"] : "white", ["textAlign"] : "center" })'
  190. )
  191. @pytest.mark.parametrize(
  192. "prop_name,var,expected",
  193. [
  194. pytest.param(
  195. "text",
  196. LiteralVar.create("hello"),
  197. None,
  198. id="text",
  199. ),
  200. pytest.param(
  201. "text",
  202. Var(_js_expr="hello", _var_type=Optional[str]),
  203. None,
  204. id="text-optional",
  205. ),
  206. pytest.param(
  207. "text",
  208. Var(_js_expr="hello", _var_type=Union[str, None]),
  209. None,
  210. id="text-union-str-none",
  211. ),
  212. pytest.param(
  213. "text",
  214. Var(_js_expr="hello", _var_type=Union[None, str]),
  215. None,
  216. id="text-union-none-str",
  217. ),
  218. pytest.param(
  219. "text",
  220. LiteralVar.create(1),
  221. TypeError,
  222. id="text-int",
  223. ),
  224. pytest.param(
  225. "number",
  226. LiteralVar.create(1),
  227. None,
  228. id="number",
  229. ),
  230. pytest.param(
  231. "number",
  232. Var(_js_expr="1", _var_type=Optional[int]),
  233. None,
  234. id="number-optional",
  235. ),
  236. pytest.param(
  237. "number",
  238. Var(_js_expr="1", _var_type=Union[int, None]),
  239. None,
  240. id="number-union-int-none",
  241. ),
  242. pytest.param(
  243. "number",
  244. Var(_js_expr="1", _var_type=Union[None, int]),
  245. None,
  246. id="number-union-none-int",
  247. ),
  248. pytest.param(
  249. "number",
  250. LiteralVar.create("1"),
  251. TypeError,
  252. id="number-str",
  253. ),
  254. pytest.param(
  255. "text_or_number",
  256. LiteralVar.create("hello"),
  257. None,
  258. id="text_or_number-str",
  259. ),
  260. pytest.param(
  261. "text_or_number",
  262. LiteralVar.create(1),
  263. None,
  264. id="text_or_number-int",
  265. ),
  266. pytest.param(
  267. "text_or_number",
  268. Var(_js_expr="hello", _var_type=Optional[str]),
  269. None,
  270. id="text_or_number-optional-str",
  271. ),
  272. pytest.param(
  273. "text_or_number",
  274. Var(_js_expr="hello", _var_type=Union[str, None]),
  275. None,
  276. id="text_or_number-union-str-none",
  277. ),
  278. pytest.param(
  279. "text_or_number",
  280. Var(_js_expr="hello", _var_type=Union[None, str]),
  281. None,
  282. id="text_or_number-union-none-str",
  283. ),
  284. pytest.param(
  285. "text_or_number",
  286. Var(_js_expr="1", _var_type=Optional[int]),
  287. None,
  288. id="text_or_number-optional-int",
  289. ),
  290. pytest.param(
  291. "text_or_number",
  292. Var(_js_expr="1", _var_type=Union[int, None]),
  293. None,
  294. id="text_or_number-union-int-none",
  295. ),
  296. pytest.param(
  297. "text_or_number",
  298. Var(_js_expr="1", _var_type=Union[None, int]),
  299. None,
  300. id="text_or_number-union-none-int",
  301. ),
  302. pytest.param(
  303. "text_or_number",
  304. LiteralVar.create(1.0),
  305. TypeError,
  306. id="text_or_number-float",
  307. ),
  308. pytest.param(
  309. "text_or_number",
  310. Var(_js_expr="hello", _var_type=Optional[Union[str, int]]),
  311. None,
  312. id="text_or_number-optional-union-str-int",
  313. ),
  314. ],
  315. )
  316. def test_create_component_prop_validation(
  317. component1: Type[Component],
  318. prop_name: str,
  319. var: Union[Var, str, int],
  320. expected: Type[Exception],
  321. ):
  322. """Test that component props are validated correctly.
  323. Args:
  324. component1: A test component.
  325. prop_name: The name of the prop.
  326. var: The value of the prop.
  327. expected: The expected exception.
  328. """
  329. ctx = pytest.raises(expected) if expected else nullcontext()
  330. kwargs = {prop_name: var}
  331. with ctx:
  332. c = component1.create(**kwargs)
  333. assert isinstance(c, component1)
  334. assert c.children == []
  335. assert c.style == {}
  336. def test_add_style(component1, component2):
  337. """Test adding a style to a component.
  338. Args:
  339. component1: A test component.
  340. component2: A test component.
  341. """
  342. style = {
  343. component1: Style({"color": "white"}),
  344. component2: Style({"color": "black"}),
  345. }
  346. c1 = component1()._add_style_recursive(style) # type: ignore
  347. c2 = component2()._add_style_recursive(style) # type: ignore
  348. assert str(c1.style["color"]) == '"white"'
  349. assert str(c2.style["color"]) == '"black"'
  350. def test_add_style_create(component1, component2):
  351. """Test that adding style works with the create method.
  352. Args:
  353. component1: A test component.
  354. component2: A test component.
  355. """
  356. style = {
  357. component1.create: Style({"color": "white"}),
  358. component2.create: Style({"color": "black"}),
  359. }
  360. c1 = component1()._add_style_recursive(style) # type: ignore
  361. c2 = component2()._add_style_recursive(style) # type: ignore
  362. assert str(c1.style["color"]) == '"white"'
  363. assert str(c2.style["color"]) == '"black"'
  364. def test_get_imports(component1, component2):
  365. """Test getting the imports of a component.
  366. Args:
  367. component1: A test component.
  368. component2: A test component.
  369. """
  370. c1 = component1.create()
  371. c2 = component2.create(c1)
  372. assert c1._get_all_imports() == {"react": [ImportVar(tag="Component")]}
  373. assert c2._get_all_imports() == {
  374. "react-redux": [ImportVar(tag="connect")],
  375. "react": [ImportVar(tag="Component")],
  376. }
  377. def test_get_custom_code(component1, component2):
  378. """Test getting the custom code of a component.
  379. Args:
  380. component1: A test component.
  381. component2: A test component.
  382. """
  383. # Check that the code gets compiled correctly.
  384. c1 = component1.create()
  385. c2 = component2.create()
  386. assert c1._get_all_custom_code() == {"console.log('component1')"}
  387. assert c2._get_all_custom_code() == {"console.log('component2')"}
  388. # Check that nesting components compiles both codes.
  389. c1 = component1.create(c2)
  390. assert c1._get_all_custom_code() == {
  391. "console.log('component1')",
  392. "console.log('component2')",
  393. }
  394. # Check that code is not duplicated.
  395. c1 = component1.create(c2, c2, c1, c1)
  396. assert c1._get_all_custom_code() == {
  397. "console.log('component1')",
  398. "console.log('component2')",
  399. }
  400. def test_get_props(component1, component2):
  401. """Test that the props are set correctly.
  402. Args:
  403. component1: A test component.
  404. component2: A test component.
  405. """
  406. assert component1.get_props() == {"text", "number", "text_or_number"}
  407. assert component2.get_props() == {"arr", "on_prop_event"}
  408. @pytest.mark.parametrize(
  409. "text,number",
  410. [
  411. ("", 0),
  412. ("test", 1),
  413. ("hi", -13),
  414. ],
  415. )
  416. def test_valid_props(component1, text: str, number: int):
  417. """Test that we can construct a component with valid props.
  418. Args:
  419. component1: A test component.
  420. text: A test string.
  421. number: A test number.
  422. """
  423. c = component1.create(text=text, number=number)
  424. assert c.text._decode() == text
  425. assert c.number._decode() == number
  426. @pytest.mark.parametrize(
  427. "text,number", [("", "bad_string"), (13, 1), ("test", [1, 2, 3])]
  428. )
  429. def test_invalid_prop_type(component1, text: str, number: int):
  430. """Test that an invalid prop type raises an error.
  431. Args:
  432. component1: A test component.
  433. text: A test string.
  434. number: A test number.
  435. """
  436. # Check that
  437. with pytest.raises(TypeError):
  438. component1.create(text=text, number=number)
  439. def test_var_props(component1, test_state):
  440. """Test that we can set a Var prop.
  441. Args:
  442. component1: A test component.
  443. test_state: A test state.
  444. """
  445. c1 = component1.create(text="hello", number=test_state.num)
  446. assert c1.number.equals(test_state.num)
  447. def test_get_event_triggers(component1, component2):
  448. """Test that we can get the triggers of a component.
  449. Args:
  450. component1: A test component.
  451. component2: A test component.
  452. """
  453. default_triggers = {
  454. EventTriggers.ON_FOCUS,
  455. EventTriggers.ON_BLUR,
  456. EventTriggers.ON_CLICK,
  457. EventTriggers.ON_CONTEXT_MENU,
  458. EventTriggers.ON_DOUBLE_CLICK,
  459. EventTriggers.ON_MOUSE_DOWN,
  460. EventTriggers.ON_MOUSE_ENTER,
  461. EventTriggers.ON_MOUSE_LEAVE,
  462. EventTriggers.ON_MOUSE_MOVE,
  463. EventTriggers.ON_MOUSE_OUT,
  464. EventTriggers.ON_MOUSE_OVER,
  465. EventTriggers.ON_MOUSE_UP,
  466. EventTriggers.ON_SCROLL,
  467. EventTriggers.ON_MOUNT,
  468. EventTriggers.ON_UNMOUNT,
  469. }
  470. assert component1().get_event_triggers().keys() == default_triggers
  471. assert (
  472. component2().get_event_triggers().keys()
  473. == {"on_open", "on_close", "on_prop_event"} | default_triggers
  474. )
  475. @pytest.fixture
  476. def test_component() -> Type[Component]:
  477. """A test component.
  478. Returns:
  479. A test component.
  480. """
  481. class TestComponent(Component):
  482. pass
  483. return TestComponent
  484. # Write a test case to check if the create method filters out None props
  485. def test_create_filters_none_props(test_component):
  486. child1 = test_component()
  487. child2 = test_component()
  488. props = {
  489. "prop1": "value1",
  490. "prop2": None,
  491. "prop3": "value3",
  492. "prop4": None,
  493. "style": {"color": "white", "text-align": "center"}, # Adding a style prop
  494. }
  495. component = test_component.create(child1, child2, **props)
  496. # Assert that None props are not present in the component's props
  497. assert "prop2" not in component.get_props()
  498. assert "prop4" not in component.get_props()
  499. # Assert that the style prop is present in the component's props
  500. assert str(component.style["color"]) == '"white"'
  501. assert str(component.style["text-align"]) == '"center"'
  502. @pytest.mark.parametrize("children", [((None,),), ("foo", ("bar", (None,)))])
  503. def test_component_create_unallowed_types(children, test_component):
  504. with pytest.raises(TypeError) as err:
  505. test_component.create(*children)
  506. assert (
  507. err.value.args[0]
  508. == "Children of Reflex components must be other components, state vars, or primitive Python types. Got child None of type <class 'NoneType'>."
  509. )
  510. @pytest.mark.parametrize(
  511. "element, expected",
  512. [
  513. (
  514. (rx.text("first_text"),),
  515. {
  516. "name": "Fragment",
  517. "props": [],
  518. "contents": "",
  519. "args": None,
  520. "special_props": [],
  521. "children": [
  522. {
  523. "name": "RadixThemesText",
  524. "props": ['as={"p"}'],
  525. "contents": "",
  526. "args": None,
  527. "special_props": [],
  528. "children": [
  529. {
  530. "name": "",
  531. "props": [],
  532. "contents": '{"first_text"}',
  533. "args": None,
  534. "special_props": [],
  535. "children": [],
  536. "autofocus": False,
  537. }
  538. ],
  539. "autofocus": False,
  540. }
  541. ],
  542. "autofocus": False,
  543. },
  544. ),
  545. (
  546. (rx.text("first_text"), rx.text("second_text")),
  547. {
  548. "args": None,
  549. "autofocus": False,
  550. "children": [
  551. {
  552. "args": None,
  553. "autofocus": False,
  554. "children": [
  555. {
  556. "args": None,
  557. "autofocus": False,
  558. "children": [],
  559. "contents": '{"first_text"}',
  560. "name": "",
  561. "props": [],
  562. "special_props": [],
  563. }
  564. ],
  565. "contents": "",
  566. "name": "RadixThemesText",
  567. "props": ['as={"p"}'],
  568. "special_props": [],
  569. },
  570. {
  571. "args": None,
  572. "autofocus": False,
  573. "children": [
  574. {
  575. "args": None,
  576. "autofocus": False,
  577. "children": [],
  578. "contents": '{"second_text"}',
  579. "name": "",
  580. "props": [],
  581. "special_props": [],
  582. }
  583. ],
  584. "contents": "",
  585. "name": "RadixThemesText",
  586. "props": ['as={"p"}'],
  587. "special_props": [],
  588. },
  589. ],
  590. "contents": "",
  591. "name": "Fragment",
  592. "props": [],
  593. "special_props": [],
  594. },
  595. ),
  596. (
  597. (rx.text("first_text"), rx.box((rx.text("second_text"),))),
  598. {
  599. "args": None,
  600. "autofocus": False,
  601. "children": [
  602. {
  603. "args": None,
  604. "autofocus": False,
  605. "children": [
  606. {
  607. "args": None,
  608. "autofocus": False,
  609. "children": [],
  610. "contents": '{"first_text"}',
  611. "name": "",
  612. "props": [],
  613. "special_props": [],
  614. }
  615. ],
  616. "contents": "",
  617. "name": "RadixThemesText",
  618. "props": ['as={"p"}'],
  619. "special_props": [],
  620. },
  621. {
  622. "args": None,
  623. "autofocus": False,
  624. "children": [
  625. {
  626. "args": None,
  627. "autofocus": False,
  628. "children": [
  629. {
  630. "args": None,
  631. "autofocus": False,
  632. "children": [
  633. {
  634. "args": None,
  635. "autofocus": False,
  636. "children": [],
  637. "contents": '{"second_text"}',
  638. "name": "",
  639. "props": [],
  640. "special_props": [],
  641. }
  642. ],
  643. "contents": "",
  644. "name": "RadixThemesText",
  645. "props": ['as={"p"}'],
  646. "special_props": [],
  647. }
  648. ],
  649. "contents": "",
  650. "name": "Fragment",
  651. "props": [],
  652. "special_props": [],
  653. }
  654. ],
  655. "contents": "",
  656. "name": "RadixThemesBox",
  657. "props": [],
  658. "special_props": [],
  659. },
  660. ],
  661. "contents": "",
  662. "name": "Fragment",
  663. "props": [],
  664. "special_props": [],
  665. },
  666. ),
  667. ],
  668. )
  669. def test_component_create_unpack_tuple_child(test_component, element, expected):
  670. """Test that component in tuples are unwrapped into an rx.Fragment.
  671. Args:
  672. test_component: Component fixture.
  673. element: The children to pass to the component.
  674. expected: The expected render dict.
  675. """
  676. comp = test_component.create(element)
  677. assert len(comp.children) == 1
  678. assert isinstance((fragment_wrapper := comp.children[0]), Fragment)
  679. assert fragment_wrapper.render() == expected
  680. class C1State(BaseState):
  681. """State for testing C1 component."""
  682. def mock_handler(self, _e, _bravo, _charlie):
  683. """Mock handler."""
  684. pass
  685. def test_component_event_trigger_arbitrary_args():
  686. """Test that we can define arbitrary types for the args of an event trigger."""
  687. class Obj(Base):
  688. custom: int = 0
  689. def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj):
  690. return [_e.target.value, bravo["nested"], charlie.custom + 42]
  691. class C1(Component):
  692. library = "/local"
  693. tag = "C1"
  694. def get_event_triggers(self) -> Dict[str, Any]:
  695. return {
  696. **super().get_event_triggers(),
  697. "on_foo": on_foo_spec,
  698. }
  699. comp = C1.create(on_foo=C1State.mock_handler)
  700. assert comp.render()["props"][0] == (
  701. "onFoo={((__e, _alpha, _bravo, _charlie) => ((addEvents("
  702. f'[(Event("{C1State.get_full_name()}.mock_handler", ({{ ["_e"] : __e["target"]["value"], ["_bravo"] : _bravo["nested"], ["_charlie"] : (_charlie["custom"] + 42) }}), ({{ }})))], '
  703. "[__e, _alpha, _bravo, _charlie], ({ })))))}"
  704. )
  705. def test_create_custom_component(my_component):
  706. """Test that we can create a custom component.
  707. Args:
  708. my_component: A test custom component.
  709. """
  710. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  711. assert component.tag == "MyComponent"
  712. assert component.get_props() == set()
  713. assert component._get_all_custom_components() == {component}
  714. def test_custom_component_hash(my_component):
  715. """Test that the hash of a custom component is correct.
  716. Args:
  717. my_component: A test custom component.
  718. """
  719. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  720. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  721. assert {component1, component2} == {component1}
  722. def test_custom_component_wrapper():
  723. """Test that the wrapper of a custom component is correct."""
  724. @custom_component
  725. def my_component(width: Var[int], color: Var[str]):
  726. return rx.box(
  727. width=width,
  728. color=color,
  729. )
  730. from reflex.components.radix.themes.typography.text import Text
  731. ccomponent = my_component(
  732. rx.text("child"), width=LiteralVar.create(1), color=LiteralVar.create("red")
  733. )
  734. assert isinstance(ccomponent, CustomComponent)
  735. assert len(ccomponent.children) == 1
  736. assert isinstance(ccomponent.children[0], Text)
  737. component = ccomponent.get_component(ccomponent)
  738. assert isinstance(component, Box)
  739. def test_invalid_event_handler_args(component2, test_state):
  740. """Test that an invalid event handler raises an error.
  741. Args:
  742. component2: A test component.
  743. test_state: A test state.
  744. """
  745. # EventHandler args must match
  746. with pytest.raises(EventHandlerArgMismatch):
  747. component2.create(on_click=test_state.do_something_arg)
  748. with pytest.raises(EventHandlerArgMismatch):
  749. component2.create(on_open=test_state.do_something)
  750. with pytest.raises(EventHandlerArgMismatch):
  751. component2.create(on_prop_event=test_state.do_something)
  752. # Multiple EventHandler args: all must match
  753. with pytest.raises(EventHandlerArgMismatch):
  754. component2.create(
  755. on_click=[test_state.do_something_arg, test_state.do_something]
  756. )
  757. with pytest.raises(EventHandlerArgMismatch):
  758. component2.create(
  759. on_open=[test_state.do_something_arg, test_state.do_something]
  760. )
  761. with pytest.raises(EventHandlerArgMismatch):
  762. component2.create(
  763. on_prop_event=[test_state.do_something_arg, test_state.do_something]
  764. )
  765. # lambda cannot return weird values.
  766. with pytest.raises(ValueError):
  767. component2.create(on_click=lambda: 1)
  768. with pytest.raises(ValueError):
  769. component2.create(on_click=lambda: [1])
  770. with pytest.raises(ValueError):
  771. component2.create(
  772. on_click=lambda: (test_state.do_something_arg(1), test_state.do_something)
  773. )
  774. # lambda signature must match event trigger.
  775. with pytest.raises(EventFnArgMismatch):
  776. component2.create(on_click=lambda _: test_state.do_something_arg(1))
  777. with pytest.raises(EventFnArgMismatch):
  778. component2.create(on_open=lambda: test_state.do_something)
  779. with pytest.raises(EventFnArgMismatch):
  780. component2.create(on_prop_event=lambda: test_state.do_something)
  781. # lambda returning EventHandler must match spec
  782. with pytest.raises(EventHandlerArgMismatch):
  783. component2.create(on_click=lambda: test_state.do_something_arg)
  784. with pytest.raises(EventHandlerArgMismatch):
  785. component2.create(on_open=lambda _: test_state.do_something)
  786. with pytest.raises(EventHandlerArgMismatch):
  787. component2.create(on_prop_event=lambda _: test_state.do_something)
  788. # Mixed EventSpec and EventHandler must match spec.
  789. with pytest.raises(EventHandlerArgMismatch):
  790. component2.create(
  791. on_click=lambda: [
  792. test_state.do_something_arg(1),
  793. test_state.do_something_arg,
  794. ]
  795. )
  796. with pytest.raises(EventHandlerArgMismatch):
  797. component2.create(
  798. on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something]
  799. )
  800. with pytest.raises(EventHandlerArgMismatch):
  801. component2.create(
  802. on_prop_event=lambda _: [
  803. test_state.do_something_arg(1),
  804. test_state.do_something,
  805. ]
  806. )
  807. def test_valid_event_handler_args(component2, test_state):
  808. """Test that an valid event handler args do not raise exception.
  809. Args:
  810. component2: A test component.
  811. test_state: A test state.
  812. """
  813. # Uncontrolled event handlers should not take args.
  814. component2.create(on_click=test_state.do_something)
  815. component2.create(on_click=test_state.do_something_arg(1))
  816. # Controlled event handlers should take args.
  817. component2.create(on_open=test_state.do_something_arg)
  818. component2.create(on_prop_event=test_state.do_something_arg)
  819. # Using a partial event spec bypasses arg validation (ignoring the args).
  820. component2.create(on_open=test_state.do_something())
  821. component2.create(on_prop_event=test_state.do_something())
  822. # lambda returning EventHandler is okay if the spec matches.
  823. component2.create(on_click=lambda: test_state.do_something)
  824. component2.create(on_open=lambda _: test_state.do_something_arg)
  825. component2.create(on_prop_event=lambda _: test_state.do_something_arg)
  826. # lambda can always return an EventSpec.
  827. component2.create(on_click=lambda: test_state.do_something_arg(1))
  828. component2.create(on_open=lambda _: test_state.do_something_arg(1))
  829. component2.create(on_prop_event=lambda _: test_state.do_something_arg(1))
  830. # Return EventSpec and EventHandler (no arg).
  831. component2.create(
  832. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  833. )
  834. component2.create(
  835. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  836. )
  837. # Return 2 EventSpec.
  838. component2.create(
  839. on_open=lambda _: [test_state.do_something_arg(1), test_state.do_something()]
  840. )
  841. component2.create(
  842. on_prop_event=lambda _: [
  843. test_state.do_something_arg(1),
  844. test_state.do_something(),
  845. ]
  846. )
  847. # Return EventHandler (1 arg) and EventSpec.
  848. component2.create(
  849. on_open=lambda _: [test_state.do_something_arg, test_state.do_something()]
  850. )
  851. component2.create(
  852. on_prop_event=lambda _: [test_state.do_something_arg, test_state.do_something()]
  853. )
  854. def test_get_hooks_nested(component1, component2, component3):
  855. """Test that a component returns hooks from child components.
  856. Args:
  857. component1: test component.
  858. component2: another component.
  859. component3: component with hooks defined.
  860. """
  861. c = component1.create(
  862. component2.create(arr=[]),
  863. component3.create(),
  864. component3.create(),
  865. component3.create(),
  866. text="a",
  867. number=1,
  868. )
  869. assert c._get_all_hooks() == component3()._get_all_hooks()
  870. def test_get_hooks_nested2(component3, component4):
  871. """Test that a component returns both when parent and child have hooks.
  872. Args:
  873. component3: component with hooks defined.
  874. component4: component with different hooks defined.
  875. """
  876. exp_hooks = {**component3()._get_all_hooks(), **component4()._get_all_hooks()}
  877. assert component3.create(component4.create())._get_all_hooks() == exp_hooks
  878. assert component4.create(component3.create())._get_all_hooks() == exp_hooks
  879. assert (
  880. component4.create(
  881. component3.create(),
  882. component4.create(),
  883. component3.create(),
  884. )._get_all_hooks()
  885. == exp_hooks
  886. )
  887. @pytest.mark.parametrize("fixture", ["component5", "component6"])
  888. def test_unsupported_child_components(fixture, request):
  889. """Test that a value error is raised when an unsupported component (a child component found in the
  890. component's invalid children list) is provided as a child.
  891. Args:
  892. fixture: the test component as a fixture.
  893. request: Pytest request.
  894. """
  895. component = request.getfixturevalue(fixture)
  896. with pytest.raises(ValueError) as err:
  897. comp = component.create(rx.text("testing component"))
  898. comp.render()
  899. assert (
  900. err.value.args[0]
  901. == f"The component `{component.__name__}` cannot have `Text` as a child component"
  902. )
  903. def test_unsupported_parent_components(component5):
  904. """Test that a value error is raised when an component is not in _valid_parents of one of its children.
  905. Args:
  906. component5: component with valid parent of "Text" only
  907. """
  908. with pytest.raises(ValueError) as err:
  909. rx.box(component5.create())
  910. assert (
  911. err.value.args[0]
  912. == f"The component `{component5.__name__}` can only be a child of the components: `{component5._valid_parents[0]}`. Got `Box` instead."
  913. )
  914. @pytest.mark.parametrize("fixture", ["component5", "component7"])
  915. def test_component_with_only_valid_children(fixture, request):
  916. """Test that a value error is raised when an unsupported component (a child component not found in the
  917. component's valid children list) is provided as a child.
  918. Args:
  919. fixture: the test component as a fixture.
  920. request: Pytest request.
  921. """
  922. component = request.getfixturevalue(fixture)
  923. with pytest.raises(ValueError) as err:
  924. comp = component.create(rx.box("testing component"))
  925. comp.render()
  926. assert (
  927. err.value.args[0]
  928. == f"The component `{component.__name__}` only allows the components: `Text` as children. "
  929. f"Got `Box` instead."
  930. )
  931. @pytest.mark.parametrize(
  932. "component,rendered",
  933. [
  934. (rx.text("hi"), '<RadixThemesText as={"p"}>\n {"hi"}\n</RadixThemesText>'),
  935. (
  936. rx.box(rx.heading("test", size="3")),
  937. '<RadixThemesBox>\n <RadixThemesHeading size={"3"}>\n {"test"}\n</RadixThemesHeading>\n</RadixThemesBox>',
  938. ),
  939. ],
  940. )
  941. def test_format_component(component, rendered):
  942. """Test that a component is formatted correctly.
  943. Args:
  944. component: The component to format.
  945. rendered: The expected rendered component.
  946. """
  947. assert str(component) == rendered
  948. def test_stateful_component(test_state):
  949. """Test that a stateful component is created correctly.
  950. Args:
  951. test_state: A test state.
  952. """
  953. text_component = rx.text(test_state.num)
  954. stateful_component = StatefulComponent.compile_from(text_component)
  955. assert isinstance(stateful_component, StatefulComponent)
  956. assert stateful_component.tag is not None
  957. assert stateful_component.tag.startswith("Text_")
  958. assert stateful_component.references == 1
  959. sc2 = StatefulComponent.compile_from(rx.text(test_state.num))
  960. assert isinstance(sc2, StatefulComponent)
  961. assert stateful_component.references == 2
  962. assert sc2.references == 2
  963. def test_stateful_component_memoize_event_trigger(test_state):
  964. """Test that a stateful component is created correctly with events.
  965. Args:
  966. test_state: A test state.
  967. """
  968. button_component = rx.button("Click me", on_click=test_state.do_something)
  969. stateful_component = StatefulComponent.compile_from(button_component)
  970. assert isinstance(stateful_component, StatefulComponent)
  971. # No event trigger? No StatefulComponent
  972. assert not isinstance(
  973. StatefulComponent.compile_from(rx.button("Click me")), StatefulComponent
  974. )
  975. def test_stateful_banner():
  976. """Test that a stateful component is created correctly with events."""
  977. connection_modal_component = rx.connection_modal()
  978. stateful_component = StatefulComponent.compile_from(connection_modal_component)
  979. assert isinstance(stateful_component, StatefulComponent)
  980. TEST_VAR = LiteralVar.create("test")._replace(
  981. merge_var_data=VarData(
  982. hooks={"useTest": None},
  983. imports={"test": [ImportVar(tag="test")]},
  984. state="Test",
  985. )
  986. )
  987. FORMATTED_TEST_VAR = LiteralVar.create(f"foo{TEST_VAR}bar")
  988. STYLE_VAR = TEST_VAR._replace(_js_expr="style")
  989. EVENT_CHAIN_VAR = TEST_VAR.to(EventChain)
  990. ARG_VAR = Var(_js_expr="arg")
  991. TEST_VAR_DICT_OF_DICT = LiteralVar.create({"a": {"b": "test"}})._replace(
  992. merge_var_data=TEST_VAR._var_data
  993. )
  994. FORMATTED_TEST_VAR_DICT_OF_DICT = LiteralVar.create(
  995. {"a": {"b": f"footestbar"}}
  996. )._replace(merge_var_data=TEST_VAR._var_data)
  997. TEST_VAR_LIST_OF_LIST = LiteralVar.create([["test"]])._replace(
  998. merge_var_data=TEST_VAR._var_data
  999. )
  1000. FORMATTED_TEST_VAR_LIST_OF_LIST = LiteralVar.create([["footestbar"]])._replace(
  1001. merge_var_data=TEST_VAR._var_data
  1002. )
  1003. TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create([[["test"]]])._replace(
  1004. merge_var_data=TEST_VAR._var_data
  1005. )
  1006. FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = LiteralVar.create(
  1007. [[["footestbar"]]]
  1008. )._replace(merge_var_data=TEST_VAR._var_data)
  1009. TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "test"}])._replace(
  1010. merge_var_data=TEST_VAR._var_data
  1011. )
  1012. FORMATTED_TEST_VAR_LIST_OF_DICT = LiteralVar.create([{"a": "footestbar"}])._replace(
  1013. merge_var_data=TEST_VAR._var_data
  1014. )
  1015. class ComponentNestedVar(Component):
  1016. """A component with nested Var types."""
  1017. dict_of_dict: Var[Dict[str, Dict[str, str]]]
  1018. list_of_list: Var[List[List[str]]]
  1019. list_of_list_of_list: Var[List[List[List[str]]]]
  1020. list_of_dict: Var[List[Dict[str, str]]]
  1021. class EventState(rx.State):
  1022. """State for testing event handlers with _get_vars."""
  1023. v: int = 42
  1024. def handler(self):
  1025. """A handler that does nothing."""
  1026. def handler2(self, arg):
  1027. """A handler that takes an arg.
  1028. Args:
  1029. arg: An arg.
  1030. """
  1031. @pytest.mark.parametrize(
  1032. ("component", "exp_vars"),
  1033. (
  1034. pytest.param(
  1035. Bare.create(TEST_VAR),
  1036. [TEST_VAR],
  1037. id="direct-bare",
  1038. ),
  1039. pytest.param(
  1040. Bare.create(f"foo{TEST_VAR}bar"),
  1041. [FORMATTED_TEST_VAR],
  1042. id="fstring-bare",
  1043. ),
  1044. pytest.param(
  1045. rx.text(as_=TEST_VAR),
  1046. [TEST_VAR],
  1047. id="direct-prop",
  1048. ),
  1049. pytest.param(
  1050. rx.heading(as_=f"foo{TEST_VAR}bar"),
  1051. [FORMATTED_TEST_VAR],
  1052. id="fstring-prop",
  1053. ),
  1054. pytest.param(
  1055. rx.fragment(id=TEST_VAR),
  1056. [TEST_VAR],
  1057. id="direct-id",
  1058. ),
  1059. pytest.param(
  1060. rx.fragment(id=f"foo{TEST_VAR}bar"),
  1061. [FORMATTED_TEST_VAR],
  1062. id="fstring-id",
  1063. ),
  1064. pytest.param(
  1065. rx.fragment(key=TEST_VAR),
  1066. [TEST_VAR],
  1067. id="direct-key",
  1068. ),
  1069. pytest.param(
  1070. rx.fragment(key=f"foo{TEST_VAR}bar"),
  1071. [FORMATTED_TEST_VAR],
  1072. id="fstring-key",
  1073. ),
  1074. pytest.param(
  1075. rx.fragment(class_name=TEST_VAR),
  1076. [TEST_VAR],
  1077. id="direct-class_name",
  1078. ),
  1079. pytest.param(
  1080. rx.fragment(class_name=f"foo{TEST_VAR}bar"),
  1081. [FORMATTED_TEST_VAR],
  1082. id="fstring-class_name",
  1083. ),
  1084. pytest.param(
  1085. rx.fragment(class_name=f"foo{TEST_VAR}bar other-class"),
  1086. [LiteralVar.create(f"{FORMATTED_TEST_VAR} other-class")],
  1087. id="fstring-dual-class_name",
  1088. ),
  1089. pytest.param(
  1090. rx.fragment(class_name=[TEST_VAR, "other-class"]),
  1091. [LiteralVar.create([TEST_VAR, "other-class"]).join(" ")],
  1092. id="fstring-dual-class_name",
  1093. ),
  1094. pytest.param(
  1095. rx.fragment(special_props=[TEST_VAR]),
  1096. [TEST_VAR],
  1097. id="direct-special_props",
  1098. ),
  1099. pytest.param(
  1100. rx.fragment(special_props=[LiteralVar.create(f"foo{TEST_VAR}bar")]),
  1101. [FORMATTED_TEST_VAR],
  1102. id="fstring-special_props",
  1103. ),
  1104. pytest.param(
  1105. # custom_attrs cannot accept a Var directly as a value
  1106. rx.fragment(custom_attrs={"href": f"{TEST_VAR}"}),
  1107. [TEST_VAR],
  1108. id="fstring-custom_attrs-nofmt",
  1109. ),
  1110. pytest.param(
  1111. rx.fragment(custom_attrs={"href": f"foo{TEST_VAR}bar"}),
  1112. [FORMATTED_TEST_VAR],
  1113. id="fstring-custom_attrs",
  1114. ),
  1115. pytest.param(
  1116. rx.fragment(background_color=TEST_VAR),
  1117. [STYLE_VAR],
  1118. id="direct-background_color",
  1119. ),
  1120. pytest.param(
  1121. rx.fragment(background_color=f"foo{TEST_VAR}bar"),
  1122. [STYLE_VAR],
  1123. id="fstring-background_color",
  1124. ),
  1125. pytest.param(
  1126. rx.fragment(style={"background_color": TEST_VAR}), # type: ignore
  1127. [STYLE_VAR],
  1128. id="direct-style-background_color",
  1129. ),
  1130. pytest.param(
  1131. rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # type: ignore
  1132. [STYLE_VAR],
  1133. id="fstring-style-background_color",
  1134. ),
  1135. pytest.param(
  1136. rx.fragment(on_click=EVENT_CHAIN_VAR), # type: ignore
  1137. [EVENT_CHAIN_VAR],
  1138. id="direct-event-chain",
  1139. ),
  1140. pytest.param(
  1141. rx.fragment(on_click=EventState.handler),
  1142. [],
  1143. id="direct-event-handler",
  1144. ),
  1145. pytest.param(
  1146. rx.fragment(on_click=EventState.handler2(TEST_VAR)), # type: ignore
  1147. [ARG_VAR, TEST_VAR],
  1148. id="direct-event-handler-arg",
  1149. ),
  1150. pytest.param(
  1151. rx.fragment(on_click=EventState.handler2(EventState.v)), # type: ignore
  1152. [ARG_VAR, EventState.v],
  1153. id="direct-event-handler-arg2",
  1154. ),
  1155. pytest.param(
  1156. rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # type: ignore
  1157. [ARG_VAR, TEST_VAR],
  1158. id="direct-event-handler-lambda",
  1159. ),
  1160. pytest.param(
  1161. ComponentNestedVar.create(dict_of_dict={"a": {"b": TEST_VAR}}),
  1162. [TEST_VAR_DICT_OF_DICT],
  1163. id="direct-dict_of_dict",
  1164. ),
  1165. pytest.param(
  1166. ComponentNestedVar.create(dict_of_dict={"a": {"b": f"foo{TEST_VAR}bar"}}),
  1167. [FORMATTED_TEST_VAR_DICT_OF_DICT],
  1168. id="fstring-dict_of_dict",
  1169. ),
  1170. pytest.param(
  1171. ComponentNestedVar.create(list_of_list=[[TEST_VAR]]),
  1172. [TEST_VAR_LIST_OF_LIST],
  1173. id="direct-list_of_list",
  1174. ),
  1175. pytest.param(
  1176. ComponentNestedVar.create(list_of_list=[[f"foo{TEST_VAR}bar"]]),
  1177. [FORMATTED_TEST_VAR_LIST_OF_LIST],
  1178. id="fstring-list_of_list",
  1179. ),
  1180. pytest.param(
  1181. ComponentNestedVar.create(list_of_list_of_list=[[[TEST_VAR]]]),
  1182. [TEST_VAR_LIST_OF_LIST_OF_LIST],
  1183. id="direct-list_of_list_of_list",
  1184. ),
  1185. pytest.param(
  1186. ComponentNestedVar.create(list_of_list_of_list=[[[f"foo{TEST_VAR}bar"]]]),
  1187. [FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST],
  1188. id="fstring-list_of_list_of_list",
  1189. ),
  1190. pytest.param(
  1191. ComponentNestedVar.create(list_of_dict=[{"a": TEST_VAR}]),
  1192. [TEST_VAR_LIST_OF_DICT],
  1193. id="direct-list_of_dict",
  1194. ),
  1195. pytest.param(
  1196. ComponentNestedVar.create(list_of_dict=[{"a": f"foo{TEST_VAR}bar"}]),
  1197. [FORMATTED_TEST_VAR_LIST_OF_DICT],
  1198. id="fstring-list_of_dict",
  1199. ),
  1200. ),
  1201. )
  1202. def test_get_vars(component, exp_vars):
  1203. comp_vars = sorted(component._get_vars(), key=lambda v: v._js_expr)
  1204. assert len(comp_vars) == len(exp_vars)
  1205. print(comp_vars, exp_vars)
  1206. for comp_var, exp_var in zip(
  1207. comp_vars,
  1208. sorted(exp_vars, key=lambda v: v._js_expr),
  1209. ):
  1210. # print(str(comp_var), str(exp_var))
  1211. # print(comp_var._get_all_var_data(), exp_var._get_all_var_data())
  1212. assert comp_var.equals(exp_var)
  1213. def test_instantiate_all_components():
  1214. """Test that all components can be instantiated."""
  1215. # These components all have required arguments and cannot be trivially instantiated.
  1216. untested_components = {
  1217. "Card",
  1218. "Cond",
  1219. "DebounceInput",
  1220. "Foreach",
  1221. "FormControl",
  1222. "Html",
  1223. "Icon",
  1224. "Match",
  1225. "Markdown",
  1226. "MultiSelect",
  1227. "Option",
  1228. "Popover",
  1229. "Radio",
  1230. "Script",
  1231. "Tag",
  1232. "Tfoot",
  1233. "Thead",
  1234. }
  1235. component_nested_list = [
  1236. *rx.RADIX_MAPPING.values(),
  1237. *rx.COMPONENTS_BASE_MAPPING.values(),
  1238. *rx.COMPONENTS_CORE_MAPPING.values(),
  1239. ]
  1240. for component_name in [
  1241. comp_name
  1242. for submodule_list in component_nested_list
  1243. for comp_name in submodule_list
  1244. ]: # type: ignore
  1245. if component_name in untested_components:
  1246. continue
  1247. component = getattr(
  1248. rx,
  1249. (
  1250. component_name
  1251. if not isinstance(component_name, tuple)
  1252. else component_name[1]
  1253. ),
  1254. )
  1255. if isinstance(component, type) and issubclass(component, Component):
  1256. component.create()
  1257. class InvalidParentComponent(Component):
  1258. """Invalid Parent Component."""
  1259. ...
  1260. class ValidComponent1(Component):
  1261. """Test valid component."""
  1262. _valid_children = ["ValidComponent2"]
  1263. class ValidComponent2(Component):
  1264. """Test valid component."""
  1265. ...
  1266. class ValidComponent3(Component):
  1267. """Test valid component."""
  1268. _valid_parents = ["ValidComponent2"]
  1269. class ValidComponent4(Component):
  1270. """Test valid component."""
  1271. _invalid_children = ["InvalidComponent"]
  1272. class InvalidComponent(Component):
  1273. """Test invalid component."""
  1274. ...
  1275. valid_component1 = ValidComponent1.create
  1276. valid_component2 = ValidComponent2.create
  1277. invalid_component = InvalidComponent.create
  1278. valid_component3 = ValidComponent3.create
  1279. invalid_parent = InvalidParentComponent.create
  1280. valid_component4 = ValidComponent4.create
  1281. def test_validate_valid_children():
  1282. valid_component1(valid_component2())
  1283. valid_component1(
  1284. rx.fragment(valid_component2()),
  1285. )
  1286. valid_component1(
  1287. rx.fragment(
  1288. rx.fragment(
  1289. rx.fragment(valid_component2()),
  1290. ),
  1291. ),
  1292. )
  1293. valid_component1(
  1294. rx.cond( # type: ignore
  1295. True,
  1296. rx.fragment(valid_component2()),
  1297. rx.fragment(
  1298. rx.foreach(LiteralVar.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore
  1299. ),
  1300. )
  1301. )
  1302. valid_component1(
  1303. rx.cond(
  1304. True,
  1305. valid_component2(),
  1306. rx.fragment(
  1307. rx.match(
  1308. "condition",
  1309. ("first", valid_component2()),
  1310. rx.fragment(valid_component2(rx.text("default"))),
  1311. )
  1312. ),
  1313. )
  1314. )
  1315. valid_component1(
  1316. rx.match(
  1317. "condition",
  1318. ("first", valid_component2()),
  1319. ("second", "third", rx.fragment(valid_component2())),
  1320. (
  1321. "fourth",
  1322. rx.cond(True, valid_component2(), rx.fragment(valid_component2())),
  1323. ),
  1324. (
  1325. "fifth",
  1326. rx.match(
  1327. "nested_condition",
  1328. ("nested_first", valid_component2()),
  1329. rx.fragment(valid_component2()),
  1330. ),
  1331. valid_component2(),
  1332. ),
  1333. )
  1334. )
  1335. def test_validate_valid_parents():
  1336. valid_component2(valid_component3())
  1337. valid_component2(
  1338. rx.fragment(valid_component3()),
  1339. )
  1340. valid_component1(
  1341. rx.fragment(
  1342. valid_component2(
  1343. rx.fragment(valid_component3()),
  1344. ),
  1345. ),
  1346. )
  1347. valid_component2(
  1348. rx.cond( # type: ignore
  1349. True,
  1350. rx.fragment(valid_component3()),
  1351. rx.fragment(
  1352. rx.foreach(
  1353. LiteralVar.create([1, 2, 3]), # type: ignore
  1354. lambda x: valid_component2(valid_component3(x)),
  1355. )
  1356. ),
  1357. )
  1358. )
  1359. valid_component2(
  1360. rx.cond(
  1361. True,
  1362. valid_component3(),
  1363. rx.fragment(
  1364. rx.match(
  1365. "condition",
  1366. ("first", valid_component3()),
  1367. rx.fragment(valid_component3(rx.text("default"))),
  1368. )
  1369. ),
  1370. )
  1371. )
  1372. valid_component2(
  1373. rx.match(
  1374. "condition",
  1375. ("first", valid_component3()),
  1376. ("second", "third", rx.fragment(valid_component3())),
  1377. (
  1378. "fourth",
  1379. rx.cond(True, valid_component3(), rx.fragment(valid_component3())),
  1380. ),
  1381. (
  1382. "fifth",
  1383. rx.match(
  1384. "nested_condition",
  1385. ("nested_first", valid_component3()),
  1386. rx.fragment(valid_component3()),
  1387. ),
  1388. valid_component3(),
  1389. ),
  1390. )
  1391. )
  1392. def test_validate_invalid_children():
  1393. with pytest.raises(ValueError):
  1394. valid_component4(invalid_component())
  1395. with pytest.raises(ValueError):
  1396. valid_component4(
  1397. rx.fragment(invalid_component()),
  1398. )
  1399. with pytest.raises(ValueError):
  1400. valid_component2(
  1401. rx.fragment(
  1402. valid_component4(
  1403. rx.fragment(invalid_component()),
  1404. ),
  1405. ),
  1406. )
  1407. with pytest.raises(ValueError):
  1408. valid_component4(
  1409. rx.cond( # type: ignore
  1410. True,
  1411. rx.fragment(invalid_component()),
  1412. rx.fragment(
  1413. rx.foreach(
  1414. LiteralVar.create([1, 2, 3]), lambda x: invalid_component(x)
  1415. ) # type: ignore
  1416. ),
  1417. )
  1418. )
  1419. with pytest.raises(ValueError):
  1420. valid_component4(
  1421. rx.cond(
  1422. True,
  1423. invalid_component(),
  1424. rx.fragment(
  1425. rx.match(
  1426. "condition",
  1427. ("first", invalid_component()),
  1428. rx.fragment(invalid_component(rx.text("default"))),
  1429. )
  1430. ),
  1431. )
  1432. )
  1433. with pytest.raises(ValueError):
  1434. valid_component4(
  1435. rx.match(
  1436. "condition",
  1437. ("first", invalid_component()),
  1438. ("second", "third", rx.fragment(invalid_component())),
  1439. (
  1440. "fourth",
  1441. rx.cond(True, invalid_component(), rx.fragment(valid_component2())),
  1442. ),
  1443. (
  1444. "fifth",
  1445. rx.match(
  1446. "nested_condition",
  1447. ("nested_first", invalid_component()),
  1448. rx.fragment(invalid_component()),
  1449. ),
  1450. invalid_component(),
  1451. ),
  1452. )
  1453. )
  1454. def test_rename_props():
  1455. """Test that _rename_props works and is inherited."""
  1456. class C1(Component):
  1457. tag = "C1"
  1458. prop1: Var[str]
  1459. prop2: Var[str]
  1460. _rename_props = {"prop1": "renamed_prop1", "prop2": "renamed_prop2"}
  1461. class C2(C1):
  1462. tag = "C2"
  1463. prop3: Var[str]
  1464. _rename_props = {"prop2": "subclass_prop2", "prop3": "renamed_prop3"}
  1465. c1 = C1.create(prop1="prop1_1", prop2="prop2_1")
  1466. rendered_c1 = c1.render()
  1467. assert 'renamed_prop1={"prop1_1"}' in rendered_c1["props"]
  1468. assert 'renamed_prop2={"prop2_1"}' in rendered_c1["props"]
  1469. c2 = C2.create(prop1="prop1_2", prop2="prop2_2", prop3="prop3_2")
  1470. rendered_c2 = c2.render()
  1471. assert 'renamed_prop1={"prop1_2"}' in rendered_c2["props"]
  1472. assert 'subclass_prop2={"prop2_2"}' in rendered_c2["props"]
  1473. assert 'renamed_prop3={"prop3_2"}' in rendered_c2["props"]
  1474. def test_custom_component_get_imports():
  1475. class Inner(Component):
  1476. tag = "Inner"
  1477. library = "inner"
  1478. class Other(Component):
  1479. tag = "Other"
  1480. library = "other"
  1481. @rx.memo
  1482. def wrapper():
  1483. return Inner.create()
  1484. @rx.memo
  1485. def outer(c: Component):
  1486. return Other.create(c)
  1487. custom_comp = wrapper()
  1488. # Inner is not imported directly, but it is imported by the custom component.
  1489. assert "inner" not in custom_comp._get_all_imports()
  1490. # The imports are only resolved during compilation.
  1491. _, _, imports_inner = compile_components(custom_comp._get_all_custom_components())
  1492. assert "inner" in imports_inner
  1493. outer_comp = outer(c=wrapper())
  1494. # Libraries are not imported directly, but are imported by the custom component.
  1495. assert "inner" not in outer_comp._get_all_imports()
  1496. assert "other" not in outer_comp._get_all_imports()
  1497. # The imports are only resolved during compilation.
  1498. _, _, imports_outer = compile_components(outer_comp._get_all_custom_components())
  1499. assert "inner" in imports_outer
  1500. assert "other" in imports_outer
  1501. def test_custom_component_declare_event_handlers_in_fields():
  1502. class ReferenceComponent(Component):
  1503. def get_event_triggers(self) -> Dict[str, Any]:
  1504. """Test controlled triggers.
  1505. Returns:
  1506. Test controlled triggers.
  1507. """
  1508. return {
  1509. **super().get_event_triggers(),
  1510. "on_a": lambda e0: [e0],
  1511. "on_b": input_event,
  1512. "on_c": lambda e0: [],
  1513. "on_d": lambda: [],
  1514. "on_e": lambda: [],
  1515. "on_f": lambda a, b, c: [c, b, a],
  1516. }
  1517. class TestComponent(Component):
  1518. on_a: EventHandler[lambda e0: [e0]]
  1519. on_b: EventHandler[input_event]
  1520. on_c: EventHandler[lambda e0: []]
  1521. on_d: EventHandler[empty_event]
  1522. on_e: EventHandler
  1523. on_f: EventHandler[lambda a, b, c: [c, b, a]]
  1524. custom_component = ReferenceComponent.create()
  1525. test_component = TestComponent.create()
  1526. custom_triggers = custom_component.get_event_triggers()
  1527. test_triggers = test_component.get_event_triggers()
  1528. assert custom_triggers.keys() == test_triggers.keys()
  1529. for trigger_name in custom_component.get_event_triggers():
  1530. for v1, v2 in zip(
  1531. parse_args_spec(test_triggers[trigger_name]),
  1532. parse_args_spec(custom_triggers[trigger_name]),
  1533. ):
  1534. assert v1.equals(v2)
  1535. def test_invalid_event_trigger():
  1536. class TriggerComponent(Component):
  1537. on_push: Var[bool]
  1538. def get_event_triggers(self) -> Dict[str, Any]:
  1539. """Test controlled triggers.
  1540. Returns:
  1541. Test controlled triggers.
  1542. """
  1543. return {
  1544. **super().get_event_triggers(),
  1545. "on_a": lambda: [],
  1546. }
  1547. trigger_comp = TriggerComponent.create
  1548. # test that these do not throw errors.
  1549. trigger_comp(on_push=True)
  1550. trigger_comp(on_a=rx.console_log("log"))
  1551. with pytest.raises(ValueError):
  1552. trigger_comp(on_b=rx.console_log("log"))
  1553. @pytest.mark.parametrize(
  1554. "tags",
  1555. (
  1556. ["Component"],
  1557. ["Component", "useState"],
  1558. [ImportVar(tag="Component")],
  1559. [ImportVar(tag="Component"), ImportVar(tag="useState")],
  1560. ["Component", ImportVar(tag="useState")],
  1561. ),
  1562. )
  1563. def test_component_add_imports(tags):
  1564. class BaseComponent(Component):
  1565. def _get_imports(self) -> ImportDict:
  1566. return {}
  1567. class Reference(Component):
  1568. def _get_imports(self) -> ParsedImportDict:
  1569. return imports.merge_imports(
  1570. super()._get_imports(),
  1571. parse_imports({"react": tags}),
  1572. {"foo": [ImportVar(tag="bar")]},
  1573. )
  1574. class TestBase(Component):
  1575. def add_imports(
  1576. self,
  1577. ) -> Dict[str, Union[str, ImportVar, List[str], List[ImportVar]]]:
  1578. return {"foo": "bar"}
  1579. class Test(TestBase):
  1580. def add_imports(
  1581. self,
  1582. ) -> Dict[str, Union[str, ImportVar, List[str], List[ImportVar]]]:
  1583. return {"react": (tags[0] if len(tags) == 1 else tags)}
  1584. baseline = Reference.create()
  1585. test = Test.create()
  1586. assert baseline._get_all_imports() == parse_imports(
  1587. {
  1588. "react": tags,
  1589. "foo": [ImportVar(tag="bar")],
  1590. }
  1591. )
  1592. assert test._get_all_imports() == baseline._get_all_imports()
  1593. def test_component_add_hooks():
  1594. class BaseComponent(Component):
  1595. def _get_hooks(self):
  1596. return "const hook1 = 42"
  1597. class ChildComponent1(BaseComponent):
  1598. pass
  1599. class GrandchildComponent1(ChildComponent1):
  1600. def add_hooks(self):
  1601. return [
  1602. "const hook2 = 43",
  1603. "const hook3 = 44",
  1604. ]
  1605. class GreatGrandchildComponent1(GrandchildComponent1):
  1606. def add_hooks(self):
  1607. return [
  1608. "const hook4 = 45",
  1609. ]
  1610. class GrandchildComponent2(ChildComponent1):
  1611. def _get_hooks(self):
  1612. return "const hook5 = 46"
  1613. class GreatGrandchildComponent2(GrandchildComponent2):
  1614. def add_hooks(self):
  1615. return [
  1616. "const hook2 = 43",
  1617. "const hook6 = 47",
  1618. ]
  1619. assert list(BaseComponent()._get_all_hooks()) == ["const hook1 = 42"]
  1620. assert list(ChildComponent1()._get_all_hooks()) == ["const hook1 = 42"]
  1621. assert list(GrandchildComponent1()._get_all_hooks()) == [
  1622. "const hook1 = 42",
  1623. "const hook2 = 43",
  1624. "const hook3 = 44",
  1625. ]
  1626. assert list(GreatGrandchildComponent1()._get_all_hooks()) == [
  1627. "const hook1 = 42",
  1628. "const hook2 = 43",
  1629. "const hook3 = 44",
  1630. "const hook4 = 45",
  1631. ]
  1632. assert list(GrandchildComponent2()._get_all_hooks()) == ["const hook5 = 46"]
  1633. assert list(GreatGrandchildComponent2()._get_all_hooks()) == [
  1634. "const hook5 = 46",
  1635. "const hook2 = 43",
  1636. "const hook6 = 47",
  1637. ]
  1638. assert list(
  1639. BaseComponent.create(
  1640. GrandchildComponent1.create(GreatGrandchildComponent2()),
  1641. GreatGrandchildComponent1(),
  1642. )._get_all_hooks(),
  1643. ) == [
  1644. "const hook1 = 42",
  1645. "const hook2 = 43",
  1646. "const hook3 = 44",
  1647. "const hook5 = 46",
  1648. "const hook6 = 47",
  1649. "const hook4 = 45",
  1650. ]
  1651. assert list(
  1652. Fragment.create(
  1653. GreatGrandchildComponent2(),
  1654. GreatGrandchildComponent1(),
  1655. )._get_all_hooks()
  1656. ) == [
  1657. "const hook5 = 46",
  1658. "const hook2 = 43",
  1659. "const hook6 = 47",
  1660. "const hook1 = 42",
  1661. "const hook3 = 44",
  1662. "const hook4 = 45",
  1663. ]
  1664. def test_component_add_custom_code():
  1665. class BaseComponent(Component):
  1666. def _get_custom_code(self):
  1667. return "const custom_code1 = 42"
  1668. class ChildComponent1(BaseComponent):
  1669. pass
  1670. class GrandchildComponent1(ChildComponent1):
  1671. def add_custom_code(self):
  1672. return [
  1673. "const custom_code2 = 43",
  1674. "const custom_code3 = 44",
  1675. ]
  1676. class GreatGrandchildComponent1(GrandchildComponent1):
  1677. def add_custom_code(self):
  1678. return [
  1679. "const custom_code4 = 45",
  1680. ]
  1681. class GrandchildComponent2(ChildComponent1):
  1682. def _get_custom_code(self):
  1683. return "const custom_code5 = 46"
  1684. class GreatGrandchildComponent2(GrandchildComponent2):
  1685. def add_custom_code(self):
  1686. return [
  1687. "const custom_code2 = 43",
  1688. "const custom_code6 = 47",
  1689. ]
  1690. assert BaseComponent()._get_all_custom_code() == {"const custom_code1 = 42"}
  1691. assert ChildComponent1()._get_all_custom_code() == {"const custom_code1 = 42"}
  1692. assert GrandchildComponent1()._get_all_custom_code() == {
  1693. "const custom_code1 = 42",
  1694. "const custom_code2 = 43",
  1695. "const custom_code3 = 44",
  1696. }
  1697. assert GreatGrandchildComponent1()._get_all_custom_code() == {
  1698. "const custom_code1 = 42",
  1699. "const custom_code2 = 43",
  1700. "const custom_code3 = 44",
  1701. "const custom_code4 = 45",
  1702. }
  1703. assert GrandchildComponent2()._get_all_custom_code() == {"const custom_code5 = 46"}
  1704. assert GreatGrandchildComponent2()._get_all_custom_code() == {
  1705. "const custom_code2 = 43",
  1706. "const custom_code5 = 46",
  1707. "const custom_code6 = 47",
  1708. }
  1709. assert BaseComponent.create(
  1710. GrandchildComponent1.create(GreatGrandchildComponent2()),
  1711. GreatGrandchildComponent1(),
  1712. )._get_all_custom_code() == {
  1713. "const custom_code1 = 42",
  1714. "const custom_code2 = 43",
  1715. "const custom_code3 = 44",
  1716. "const custom_code4 = 45",
  1717. "const custom_code5 = 46",
  1718. "const custom_code6 = 47",
  1719. }
  1720. assert Fragment.create(
  1721. GreatGrandchildComponent2(),
  1722. GreatGrandchildComponent1(),
  1723. )._get_all_custom_code() == {
  1724. "const custom_code1 = 42",
  1725. "const custom_code2 = 43",
  1726. "const custom_code3 = 44",
  1727. "const custom_code4 = 45",
  1728. "const custom_code5 = 46",
  1729. "const custom_code6 = 47",
  1730. }
  1731. def test_component_add_hooks_var():
  1732. class HookComponent(Component):
  1733. def add_hooks(self):
  1734. return [
  1735. "const hook3 = useRef(null)",
  1736. "const hook1 = 42",
  1737. Var(
  1738. _js_expr="useEffect(() => () => {}, [])",
  1739. _var_data=VarData(
  1740. hooks={
  1741. "const hook2 = 43": None,
  1742. "const hook3 = useRef(null)": None,
  1743. },
  1744. imports={"react": [ImportVar(tag="useEffect")]},
  1745. ),
  1746. ),
  1747. Var(
  1748. _js_expr="const hook3 = useRef(null)",
  1749. _var_data=VarData(imports={"react": [ImportVar(tag="useRef")]}),
  1750. ),
  1751. ]
  1752. assert list(HookComponent()._get_all_hooks()) == [
  1753. "const hook3 = useRef(null)",
  1754. "const hook1 = 42",
  1755. "const hook2 = 43",
  1756. "useEffect(() => () => {}, [])",
  1757. ]
  1758. imports = HookComponent()._get_all_imports()
  1759. assert len(imports) == 1
  1760. assert "react" in imports
  1761. assert len(imports["react"]) == 2
  1762. assert ImportVar(tag="useRef") in imports["react"]
  1763. assert ImportVar(tag="useEffect") in imports["react"]
  1764. def test_add_style_embedded_vars(test_state: BaseState):
  1765. """Test that add_style works with embedded vars when returning a plain dict.
  1766. Args:
  1767. test_state: A test state.
  1768. """
  1769. v0 = LiteralVar.create("parent")._replace(
  1770. merge_var_data=VarData(hooks={"useParent": None}), # type: ignore
  1771. )
  1772. v1 = rx.color("plum", 10)
  1773. v2 = LiteralVar.create("text")._replace(
  1774. merge_var_data=VarData(hooks={"useText": None}), # type: ignore
  1775. )
  1776. class ParentComponent(Component):
  1777. def add_style(self):
  1778. return Style(
  1779. {
  1780. "fake_parent": v0,
  1781. }
  1782. )
  1783. class StyledComponent(ParentComponent):
  1784. tag = "StyledComponent"
  1785. def add_style(self):
  1786. return {
  1787. "color": v1,
  1788. "fake": v2,
  1789. "margin": f"{test_state.num}%",
  1790. }
  1791. page = rx.vstack(StyledComponent.create())
  1792. page._add_style_recursive(Style())
  1793. assert (
  1794. f"const {test_state.get_name()} = useContext(StateContexts.{test_state.get_name()})"
  1795. in page._get_all_hooks_internal()
  1796. )
  1797. assert "useText" in page._get_all_hooks_internal()
  1798. assert "useParent" in page._get_all_hooks_internal()
  1799. assert (
  1800. str(page).count(
  1801. f'css={{({{ ["fakeParent"] : "parent", ["color"] : "var(--plum-10)", ["fake"] : "text", ["margin"] : ({test_state.get_name()}.num+"%") }})}}'
  1802. )
  1803. == 1
  1804. )
  1805. def test_add_style_foreach():
  1806. class StyledComponent(Component):
  1807. tag = "StyledComponent"
  1808. ix: Var[int]
  1809. def add_style(self):
  1810. return Style({"color": "red"})
  1811. page = rx.vstack(rx.foreach(Var.range(3), lambda i: StyledComponent.create(i)))
  1812. page._add_style_recursive(Style())
  1813. # Expect only a single child of the foreach on the python side
  1814. assert len(page.children[0].children) == 1
  1815. # Expect the style to be added to the child of the foreach
  1816. assert 'css={({ ["color"] : "red" })}' in str(page.children[0].children[0])
  1817. # Expect only one instance of this CSS dict in the rendered page
  1818. assert str(page).count('css={({ ["color"] : "red" })}') == 1
  1819. class TriggerState(rx.State):
  1820. """Test state with event handlers."""
  1821. def do_something(self):
  1822. """Sample event handler."""
  1823. pass
  1824. @pytest.mark.parametrize(
  1825. "component, output",
  1826. [
  1827. (rx.box(rx.text("random text")), False),
  1828. (
  1829. rx.box(rx.text("random text", on_click=rx.console_log("log"))),
  1830. False,
  1831. ),
  1832. (
  1833. rx.box(
  1834. rx.text("random text", on_click=TriggerState.do_something),
  1835. rx.text(
  1836. "random text",
  1837. on_click=Var(_js_expr="toggleColorMode").to(EventChain),
  1838. ),
  1839. ),
  1840. True,
  1841. ),
  1842. (
  1843. rx.box(
  1844. rx.text("random text", on_click=rx.console_log("log")),
  1845. rx.text(
  1846. "random text",
  1847. on_click=Var(_js_expr="toggleColorMode").to(EventChain),
  1848. ),
  1849. ),
  1850. False,
  1851. ),
  1852. (
  1853. rx.box(rx.text("random text", on_click=TriggerState.do_something)),
  1854. True,
  1855. ),
  1856. (
  1857. rx.box(
  1858. rx.text(
  1859. "random text",
  1860. on_click=[rx.console_log("log"), rx.window_alert("alert")],
  1861. ),
  1862. ),
  1863. False,
  1864. ),
  1865. (
  1866. rx.box(
  1867. rx.text(
  1868. "random text",
  1869. on_click=[rx.console_log("log"), TriggerState.do_something],
  1870. ),
  1871. ),
  1872. True,
  1873. ),
  1874. (
  1875. rx.box(
  1876. rx.text(
  1877. "random text",
  1878. on_blur=lambda: TriggerState.do_something,
  1879. ),
  1880. ),
  1881. True,
  1882. ),
  1883. ],
  1884. )
  1885. def test_has_state_event_triggers(component, output):
  1886. assert component._has_stateful_event_triggers() == output