test_component.py 62 KB

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