test_component.py 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271
  1. from typing import Any, Dict, List, Type
  2. import pytest
  3. import reflex as rx
  4. from reflex.base import Base
  5. from reflex.components.base.bare import Bare
  6. from reflex.components.chakra.layout.box import Box
  7. from reflex.components.component import (
  8. Component,
  9. CustomComponent,
  10. StatefulComponent,
  11. custom_component,
  12. )
  13. from reflex.constants import EventTriggers
  14. from reflex.event import EventChain, EventHandler
  15. from reflex.state import BaseState
  16. from reflex.style import Style
  17. from reflex.utils import imports
  18. from reflex.utils.imports import ImportVar
  19. from reflex.vars import Var, VarData
  20. @pytest.fixture
  21. def test_state():
  22. class TestState(BaseState):
  23. num: int
  24. def do_something(self):
  25. pass
  26. def do_something_arg(self, arg):
  27. pass
  28. return TestState
  29. @pytest.fixture
  30. def component1() -> Type[Component]:
  31. """A test component.
  32. Returns:
  33. A test component.
  34. """
  35. class TestComponent1(Component):
  36. # A test string prop.
  37. text: Var[str]
  38. # A test number prop.
  39. number: Var[int]
  40. def _get_imports(self) -> imports.ImportDict:
  41. return {"react": [ImportVar(tag="Component")]}
  42. def _get_custom_code(self) -> str:
  43. return "console.log('component1')"
  44. return TestComponent1
  45. @pytest.fixture
  46. def component2() -> Type[Component]:
  47. """A test component.
  48. Returns:
  49. A test component.
  50. """
  51. class TestComponent2(Component):
  52. # A test list prop.
  53. arr: Var[List[str]]
  54. def get_event_triggers(self) -> Dict[str, Any]:
  55. """Test controlled triggers.
  56. Returns:
  57. Test controlled triggers.
  58. """
  59. return {
  60. **super().get_event_triggers(),
  61. "on_open": lambda e0: [e0],
  62. "on_close": lambda e0: [e0],
  63. }
  64. def _get_imports(self) -> imports.ImportDict:
  65. return {"react-redux": [ImportVar(tag="connect")]}
  66. def _get_custom_code(self) -> str:
  67. return "console.log('component2')"
  68. return TestComponent2
  69. @pytest.fixture
  70. def component3() -> Type[Component]:
  71. """A test component with hook defined.
  72. Returns:
  73. A test component.
  74. """
  75. class TestComponent3(Component):
  76. def _get_hooks(self) -> str:
  77. return "const a = () => true"
  78. return TestComponent3
  79. @pytest.fixture
  80. def component4() -> Type[Component]:
  81. """A test component with hook defined.
  82. Returns:
  83. A test component.
  84. """
  85. class TestComponent4(Component):
  86. def _get_hooks(self) -> str:
  87. return "const b = () => false"
  88. return TestComponent4
  89. @pytest.fixture
  90. def component5() -> Type[Component]:
  91. """A test component.
  92. Returns:
  93. A test component.
  94. """
  95. class TestComponent5(Component):
  96. tag = "RandomComponent"
  97. _invalid_children: List[str] = ["Text"]
  98. _valid_children: List[str] = ["Text"]
  99. _valid_parents: List[str] = ["Text"]
  100. return TestComponent5
  101. @pytest.fixture
  102. def component6() -> Type[Component]:
  103. """A test component.
  104. Returns:
  105. A test component.
  106. """
  107. class TestComponent6(Component):
  108. tag = "RandomComponent"
  109. _invalid_children: List[str] = ["Text"]
  110. return TestComponent6
  111. @pytest.fixture
  112. def component7() -> Type[Component]:
  113. """A test component.
  114. Returns:
  115. A test component.
  116. """
  117. class TestComponent7(Component):
  118. tag = "RandomComponent"
  119. _valid_children: List[str] = ["Text"]
  120. return TestComponent7
  121. @pytest.fixture
  122. def on_click1() -> EventHandler:
  123. """A sample on click function.
  124. Returns:
  125. A sample on click function.
  126. """
  127. def on_click1():
  128. pass
  129. return EventHandler(fn=on_click1)
  130. @pytest.fixture
  131. def on_click2() -> EventHandler:
  132. """A sample on click function.
  133. Returns:
  134. A sample on click function.
  135. """
  136. def on_click2():
  137. pass
  138. return EventHandler(fn=on_click2)
  139. @pytest.fixture
  140. def my_component():
  141. """A test component function.
  142. Returns:
  143. A test component function.
  144. """
  145. def my_component(prop1: Var[str], prop2: Var[int]):
  146. return Box.create(prop1, prop2)
  147. return my_component
  148. def test_set_style_attrs(component1):
  149. """Test that style attributes are set in the dict.
  150. Args:
  151. component1: A test component.
  152. """
  153. component = component1(color="white", text_align="center")
  154. assert component.style["color"] == "white"
  155. assert component.style["textAlign"] == "center"
  156. def test_custom_attrs(component1):
  157. """Test that custom attributes are set in the dict.
  158. Args:
  159. component1: A test component.
  160. """
  161. component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
  162. assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
  163. def test_create_component(component1):
  164. """Test that the component is created correctly.
  165. Args:
  166. component1: A test component.
  167. """
  168. children = [component1() for _ in range(3)]
  169. attrs = {"color": "white", "text_align": "center"}
  170. c = component1.create(*children, **attrs)
  171. assert isinstance(c, component1)
  172. assert c.children == children
  173. assert c.style == {"color": "white", "textAlign": "center"}
  174. def test_add_style(component1, component2):
  175. """Test adding a style to a component.
  176. Args:
  177. component1: A test component.
  178. component2: A test component.
  179. """
  180. style = {
  181. component1: Style({"color": "white"}),
  182. component2: Style({"color": "black"}),
  183. }
  184. c1 = component1().add_style(style) # type: ignore
  185. c2 = component2().add_style(style) # type: ignore
  186. assert c1.style["color"] == "white"
  187. assert c2.style["color"] == "black"
  188. def test_add_style_create(component1, component2):
  189. """Test that adding style works with the create method.
  190. Args:
  191. component1: A test component.
  192. component2: A test component.
  193. """
  194. style = {
  195. component1.create: Style({"color": "white"}),
  196. component2.create: Style({"color": "black"}),
  197. }
  198. c1 = component1().add_style(style) # type: ignore
  199. c2 = component2().add_style(style) # type: ignore
  200. assert c1.style["color"] == "white"
  201. assert c2.style["color"] == "black"
  202. def test_get_imports(component1, component2):
  203. """Test getting the imports of a component.
  204. Args:
  205. component1: A test component.
  206. component2: A test component.
  207. """
  208. c1 = component1.create()
  209. c2 = component2.create(c1)
  210. assert c1.get_imports() == {"react": [ImportVar(tag="Component")]}
  211. assert c2.get_imports() == {
  212. "react-redux": [ImportVar(tag="connect")],
  213. "react": [ImportVar(tag="Component")],
  214. }
  215. def test_get_custom_code(component1, component2):
  216. """Test getting the custom code of a component.
  217. Args:
  218. component1: A test component.
  219. component2: A test component.
  220. """
  221. # Check that the code gets compiled correctly.
  222. c1 = component1.create()
  223. c2 = component2.create()
  224. assert c1.get_custom_code() == {"console.log('component1')"}
  225. assert c2.get_custom_code() == {"console.log('component2')"}
  226. # Check that nesting components compiles both codes.
  227. c1 = component1.create(c2)
  228. assert c1.get_custom_code() == {
  229. "console.log('component1')",
  230. "console.log('component2')",
  231. }
  232. # Check that code is not duplicated.
  233. c1 = component1.create(c2, c2, c1, c1)
  234. assert c1.get_custom_code() == {
  235. "console.log('component1')",
  236. "console.log('component2')",
  237. }
  238. def test_get_props(component1, component2):
  239. """Test that the props are set correctly.
  240. Args:
  241. component1: A test component.
  242. component2: A test component.
  243. """
  244. assert component1.get_props() == {"text", "number"}
  245. assert component2.get_props() == {"arr"}
  246. @pytest.mark.parametrize(
  247. "text,number",
  248. [
  249. ("", 0),
  250. ("test", 1),
  251. ("hi", -13),
  252. ],
  253. )
  254. def test_valid_props(component1, text: str, number: int):
  255. """Test that we can construct a component with valid props.
  256. Args:
  257. component1: A test component.
  258. text: A test string.
  259. number: A test number.
  260. """
  261. c = component1.create(text=text, number=number)
  262. assert c.text._decode() == text
  263. assert c.number._decode() == number
  264. @pytest.mark.parametrize(
  265. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  266. )
  267. def test_invalid_prop_type(component1, text: str, number: int):
  268. """Test that an invalid prop type raises an error.
  269. Args:
  270. component1: A test component.
  271. text: A test string.
  272. number: A test number.
  273. """
  274. # Check that
  275. with pytest.raises(TypeError):
  276. component1.create(text=text, number=number)
  277. def test_var_props(component1, test_state):
  278. """Test that we can set a Var prop.
  279. Args:
  280. component1: A test component.
  281. test_state: A test state.
  282. """
  283. c1 = component1.create(text="hello", number=test_state.num)
  284. assert c1.number.equals(test_state.num)
  285. def test_get_event_triggers(component1, component2):
  286. """Test that we can get the triggers of a component.
  287. Args:
  288. component1: A test component.
  289. component2: A test component.
  290. """
  291. default_triggers = {
  292. EventTriggers.ON_FOCUS,
  293. EventTriggers.ON_BLUR,
  294. EventTriggers.ON_CLICK,
  295. EventTriggers.ON_CONTEXT_MENU,
  296. EventTriggers.ON_DOUBLE_CLICK,
  297. EventTriggers.ON_MOUSE_DOWN,
  298. EventTriggers.ON_MOUSE_ENTER,
  299. EventTriggers.ON_MOUSE_LEAVE,
  300. EventTriggers.ON_MOUSE_MOVE,
  301. EventTriggers.ON_MOUSE_OUT,
  302. EventTriggers.ON_MOUSE_OVER,
  303. EventTriggers.ON_MOUSE_UP,
  304. EventTriggers.ON_SCROLL,
  305. EventTriggers.ON_MOUNT,
  306. EventTriggers.ON_UNMOUNT,
  307. }
  308. assert set(component1().get_event_triggers().keys()) == default_triggers
  309. assert (
  310. component2().get_event_triggers().keys()
  311. == {"on_open", "on_close"} | default_triggers
  312. )
  313. class C1State(BaseState):
  314. """State for testing C1 component."""
  315. def mock_handler(self, _e, _bravo, _charlie):
  316. """Mock handler."""
  317. pass
  318. def test_component_event_trigger_arbitrary_args():
  319. """Test that we can define arbitrary types for the args of an event trigger."""
  320. class Obj(Base):
  321. custom: int = 0
  322. def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj):
  323. return [_e.target.value, bravo["nested"], charlie.custom + 42]
  324. class C1(Component):
  325. library = "/local"
  326. tag = "C1"
  327. def get_event_triggers(self) -> Dict[str, Any]:
  328. return {
  329. **super().get_event_triggers(),
  330. "on_foo": on_foo_spec,
  331. }
  332. comp = C1.create(on_foo=C1State.mock_handler)
  333. assert comp.render()["props"][0] == (
  334. "onFoo={(__e,_alpha,_bravo,_charlie) => addEvents("
  335. '[Event("c1_state.mock_handler", {_e:__e.target.value,_bravo:_bravo["nested"],_charlie:((_charlie.custom) + (42))})], '
  336. "(__e,_alpha,_bravo,_charlie), {})}"
  337. )
  338. def test_create_custom_component(my_component):
  339. """Test that we can create a custom component.
  340. Args:
  341. my_component: A test custom component.
  342. """
  343. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  344. assert component.tag == "MyComponent"
  345. assert component.get_props() == set()
  346. assert component.get_custom_components() == {component}
  347. def test_custom_component_hash(my_component):
  348. """Test that the hash of a custom component is correct.
  349. Args:
  350. my_component: A test custom component.
  351. """
  352. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  353. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  354. assert {component1, component2} == {component1}
  355. def test_custom_component_wrapper():
  356. """Test that the wrapper of a custom component is correct."""
  357. @custom_component
  358. def my_component(width: Var[int], color: Var[str]):
  359. return rx.box(
  360. width=width,
  361. color=color,
  362. )
  363. from reflex.components.radix.themes.typography.text import Text
  364. ccomponent = my_component(
  365. rx.text("child"), width=Var.create(1), color=Var.create("red")
  366. )
  367. assert isinstance(ccomponent, CustomComponent)
  368. assert len(ccomponent.children) == 1
  369. assert isinstance(ccomponent.children[0], Text)
  370. component = ccomponent.get_component(ccomponent)
  371. assert isinstance(component, Box)
  372. def test_invalid_event_handler_args(component2, test_state):
  373. """Test that an invalid event handler raises an error.
  374. Args:
  375. component2: A test component.
  376. test_state: A test state.
  377. """
  378. # Uncontrolled event handlers should not take args.
  379. # This is okay.
  380. component2.create(on_click=test_state.do_something)
  381. # This is not okay.
  382. with pytest.raises(ValueError):
  383. component2.create(on_click=test_state.do_something_arg)
  384. component2.create(on_open=test_state.do_something)
  385. component2.create(
  386. on_open=[test_state.do_something_arg, test_state.do_something]
  387. )
  388. # However lambdas are okay.
  389. component2.create(on_click=lambda: test_state.do_something_arg(1))
  390. component2.create(
  391. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  392. )
  393. component2.create(
  394. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  395. )
  396. # Controlled event handlers should take args.
  397. # This is okay.
  398. component2.create(on_open=test_state.do_something_arg)
  399. def test_get_hooks_nested(component1, component2, component3):
  400. """Test that a component returns hooks from child components.
  401. Args:
  402. component1: test component.
  403. component2: another component.
  404. component3: component with hooks defined.
  405. """
  406. c = component1.create(
  407. component2.create(arr=[]),
  408. component3.create(),
  409. component3.create(),
  410. component3.create(),
  411. text="a",
  412. number=1,
  413. )
  414. assert c.get_hooks() == component3().get_hooks()
  415. def test_get_hooks_nested2(component3, component4):
  416. """Test that a component returns both when parent and child have hooks.
  417. Args:
  418. component3: component with hooks defined.
  419. component4: component with different hooks defined.
  420. """
  421. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  422. assert component3.create(component4.create()).get_hooks() == exp_hooks
  423. assert component4.create(component3.create()).get_hooks() == exp_hooks
  424. assert (
  425. component4.create(
  426. component3.create(),
  427. component4.create(),
  428. component3.create(),
  429. ).get_hooks()
  430. == exp_hooks
  431. )
  432. @pytest.mark.parametrize("fixture", ["component5", "component6"])
  433. def test_unsupported_child_components(fixture, request):
  434. """Test that a value error is raised when an unsupported component (a child component found in the
  435. component's invalid children list) is provided as a child.
  436. Args:
  437. fixture: the test component as a fixture.
  438. request: Pytest request.
  439. """
  440. component = request.getfixturevalue(fixture)
  441. with pytest.raises(ValueError) as err:
  442. comp = component.create(rx.text("testing component"))
  443. comp.render()
  444. assert (
  445. err.value.args[0]
  446. == f"The component `{component.__name__}` cannot have `Text` as a child component"
  447. )
  448. def test_unsupported_parent_components(component5):
  449. """Test that a value error is raised when an component is not in _valid_parents of one of its children.
  450. Args:
  451. component5: component with valid parent of "Text" only
  452. """
  453. with pytest.raises(ValueError) as err:
  454. rx.box(component5.create())
  455. assert (
  456. err.value.args[0]
  457. == f"The component `{component5.__name__}` can only be a child of the components: `{component5._valid_parents[0]}`. Got `Box` instead."
  458. )
  459. @pytest.mark.parametrize("fixture", ["component5", "component7"])
  460. def test_component_with_only_valid_children(fixture, request):
  461. """Test that a value error is raised when an unsupported component (a child component not found in the
  462. component's valid children list) is provided as a child.
  463. Args:
  464. fixture: the test component as a fixture.
  465. request: Pytest request.
  466. """
  467. component = request.getfixturevalue(fixture)
  468. with pytest.raises(ValueError) as err:
  469. comp = component.create(rx.box("testing component"))
  470. comp.render()
  471. assert (
  472. err.value.args[0]
  473. == f"The component `{component.__name__}` only allows the components: `Text` as children. "
  474. f"Got `Box` instead."
  475. )
  476. @pytest.mark.parametrize(
  477. "component,rendered",
  478. [
  479. (rx.text("hi"), "<RadixThemesText as={`p`}>\n {`hi`}\n</RadixThemesText>"),
  480. (
  481. rx.box(rx.chakra.heading("test", size="md")),
  482. "<RadixThemesBox>\n <Heading size={`md`}>\n {`test`}\n</Heading>\n</RadixThemesBox>",
  483. ),
  484. ],
  485. )
  486. def test_format_component(component, rendered):
  487. """Test that a component is formatted correctly.
  488. Args:
  489. component: The component to format.
  490. rendered: The expected rendered component.
  491. """
  492. assert str(component) == rendered
  493. def test_stateful_component(test_state):
  494. """Test that a stateful component is created correctly.
  495. Args:
  496. test_state: A test state.
  497. """
  498. text_component = rx.text(test_state.num)
  499. stateful_component = StatefulComponent.compile_from(text_component)
  500. assert isinstance(stateful_component, StatefulComponent)
  501. assert stateful_component.tag is not None
  502. assert stateful_component.tag.startswith("Text_")
  503. assert stateful_component.references == 1
  504. sc2 = StatefulComponent.compile_from(rx.text(test_state.num))
  505. assert isinstance(sc2, StatefulComponent)
  506. assert stateful_component.references == 2
  507. assert sc2.references == 2
  508. def test_stateful_component_memoize_event_trigger(test_state):
  509. """Test that a stateful component is created correctly with events.
  510. Args:
  511. test_state: A test state.
  512. """
  513. button_component = rx.button("Click me", on_click=test_state.do_something)
  514. stateful_component = StatefulComponent.compile_from(button_component)
  515. assert isinstance(stateful_component, StatefulComponent)
  516. # No event trigger? No StatefulComponent
  517. assert not isinstance(
  518. StatefulComponent.compile_from(rx.button("Click me")), StatefulComponent
  519. )
  520. def test_stateful_banner():
  521. """Test that a stateful component is created correctly with events."""
  522. connection_modal_component = rx.connection_modal()
  523. stateful_component = StatefulComponent.compile_from(connection_modal_component)
  524. assert isinstance(stateful_component, StatefulComponent)
  525. TEST_VAR = Var.create_safe("test")._replace(
  526. merge_var_data=VarData(
  527. hooks={"useTest"},
  528. imports={"test": {ImportVar(tag="test")}},
  529. state="Test",
  530. interpolations=[],
  531. )
  532. )
  533. FORMATTED_TEST_VAR = Var.create(f"foo{TEST_VAR}bar")
  534. STYLE_VAR = TEST_VAR._replace(_var_name="style", _var_is_local=False)
  535. EVENT_CHAIN_VAR = TEST_VAR._replace(_var_type=EventChain)
  536. ARG_VAR = Var.create("arg")
  537. TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": "test"}})._replace(
  538. merge_var_data=TEST_VAR._var_data
  539. )
  540. FORMATTED_TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": f"footestbar"}})._replace(
  541. merge_var_data=TEST_VAR._var_data
  542. )
  543. TEST_VAR_LIST_OF_LIST = Var.create_safe([["test"]])._replace(
  544. merge_var_data=TEST_VAR._var_data
  545. )
  546. FORMATTED_TEST_VAR_LIST_OF_LIST = Var.create_safe([["footestbar"]])._replace(
  547. merge_var_data=TEST_VAR._var_data
  548. )
  549. TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["test"]]])._replace(
  550. merge_var_data=TEST_VAR._var_data
  551. )
  552. FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["footestbar"]]])._replace(
  553. merge_var_data=TEST_VAR._var_data
  554. )
  555. TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "test"}])._replace(
  556. merge_var_data=TEST_VAR._var_data
  557. )
  558. FORMATTED_TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "footestbar"}])._replace(
  559. merge_var_data=TEST_VAR._var_data
  560. )
  561. class ComponentNestedVar(Component):
  562. """A component with nested Var types."""
  563. dict_of_dict: Var[Dict[str, Dict[str, str]]]
  564. list_of_list: Var[List[List[str]]]
  565. list_of_list_of_list: Var[List[List[List[str]]]]
  566. list_of_dict: Var[List[Dict[str, str]]]
  567. class EventState(rx.State):
  568. """State for testing event handlers with _get_vars."""
  569. v: int = 42
  570. def handler(self):
  571. """A handler that does nothing."""
  572. def handler2(self, arg):
  573. """A handler that takes an arg.
  574. Args:
  575. arg: An arg.
  576. """
  577. @pytest.mark.parametrize(
  578. ("component", "exp_vars"),
  579. (
  580. pytest.param(
  581. Bare.create(TEST_VAR),
  582. [TEST_VAR],
  583. id="direct-bare",
  584. ),
  585. pytest.param(
  586. Bare.create(f"foo{TEST_VAR}bar"),
  587. [FORMATTED_TEST_VAR],
  588. id="fstring-bare",
  589. ),
  590. pytest.param(
  591. rx.text(as_=TEST_VAR),
  592. [TEST_VAR],
  593. id="direct-prop",
  594. ),
  595. pytest.param(
  596. rx.heading(as_=f"foo{TEST_VAR}bar"),
  597. [FORMATTED_TEST_VAR],
  598. id="fstring-prop",
  599. ),
  600. pytest.param(
  601. rx.fragment(id=TEST_VAR),
  602. [TEST_VAR],
  603. id="direct-id",
  604. ),
  605. pytest.param(
  606. rx.fragment(id=f"foo{TEST_VAR}bar"),
  607. [FORMATTED_TEST_VAR],
  608. id="fstring-id",
  609. ),
  610. pytest.param(
  611. rx.fragment(key=TEST_VAR),
  612. [TEST_VAR],
  613. id="direct-key",
  614. ),
  615. pytest.param(
  616. rx.fragment(key=f"foo{TEST_VAR}bar"),
  617. [FORMATTED_TEST_VAR],
  618. id="fstring-key",
  619. ),
  620. pytest.param(
  621. rx.fragment(class_name=TEST_VAR),
  622. [TEST_VAR],
  623. id="direct-class_name",
  624. ),
  625. pytest.param(
  626. rx.fragment(class_name=f"foo{TEST_VAR}bar"),
  627. [FORMATTED_TEST_VAR],
  628. id="fstring-class_name",
  629. ),
  630. pytest.param(
  631. rx.fragment(special_props={TEST_VAR}),
  632. [TEST_VAR],
  633. id="direct-special_props",
  634. ),
  635. pytest.param(
  636. rx.fragment(special_props={Var.create(f"foo{TEST_VAR}bar")}),
  637. [FORMATTED_TEST_VAR],
  638. id="fstring-special_props",
  639. ),
  640. pytest.param(
  641. # custom_attrs cannot accept a Var directly as a value
  642. rx.fragment(custom_attrs={"href": f"{TEST_VAR}"}),
  643. [TEST_VAR],
  644. id="fstring-custom_attrs-nofmt",
  645. ),
  646. pytest.param(
  647. rx.fragment(custom_attrs={"href": f"foo{TEST_VAR}bar"}),
  648. [FORMATTED_TEST_VAR],
  649. id="fstring-custom_attrs",
  650. ),
  651. pytest.param(
  652. rx.fragment(background_color=TEST_VAR),
  653. [STYLE_VAR],
  654. id="direct-background_color",
  655. ),
  656. pytest.param(
  657. rx.fragment(background_color=f"foo{TEST_VAR}bar"),
  658. [STYLE_VAR],
  659. id="fstring-background_color",
  660. ),
  661. pytest.param(
  662. rx.fragment(style={"background_color": TEST_VAR}), # type: ignore
  663. [STYLE_VAR],
  664. id="direct-style-background_color",
  665. ),
  666. pytest.param(
  667. rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # type: ignore
  668. [STYLE_VAR],
  669. id="fstring-style-background_color",
  670. ),
  671. pytest.param(
  672. rx.fragment(on_click=EVENT_CHAIN_VAR), # type: ignore
  673. [EVENT_CHAIN_VAR],
  674. id="direct-event-chain",
  675. ),
  676. pytest.param(
  677. rx.fragment(on_click=EventState.handler),
  678. [],
  679. id="direct-event-handler",
  680. ),
  681. pytest.param(
  682. rx.fragment(on_click=EventState.handler2(TEST_VAR)), # type: ignore
  683. [ARG_VAR, TEST_VAR],
  684. id="direct-event-handler-arg",
  685. ),
  686. pytest.param(
  687. rx.fragment(on_click=EventState.handler2(EventState.v)), # type: ignore
  688. [ARG_VAR, EventState.v],
  689. id="direct-event-handler-arg2",
  690. ),
  691. pytest.param(
  692. rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # type: ignore
  693. [ARG_VAR, TEST_VAR],
  694. id="direct-event-handler-lambda",
  695. ),
  696. pytest.param(
  697. ComponentNestedVar.create(dict_of_dict={"a": {"b": TEST_VAR}}),
  698. [TEST_VAR_DICT_OF_DICT],
  699. id="direct-dict_of_dict",
  700. ),
  701. pytest.param(
  702. ComponentNestedVar.create(dict_of_dict={"a": {"b": f"foo{TEST_VAR}bar"}}),
  703. [FORMATTED_TEST_VAR_DICT_OF_DICT],
  704. id="fstring-dict_of_dict",
  705. ),
  706. pytest.param(
  707. ComponentNestedVar.create(list_of_list=[[TEST_VAR]]),
  708. [TEST_VAR_LIST_OF_LIST],
  709. id="direct-list_of_list",
  710. ),
  711. pytest.param(
  712. ComponentNestedVar.create(list_of_list=[[f"foo{TEST_VAR}bar"]]),
  713. [FORMATTED_TEST_VAR_LIST_OF_LIST],
  714. id="fstring-list_of_list",
  715. ),
  716. pytest.param(
  717. ComponentNestedVar.create(list_of_list_of_list=[[[TEST_VAR]]]),
  718. [TEST_VAR_LIST_OF_LIST_OF_LIST],
  719. id="direct-list_of_list_of_list",
  720. ),
  721. pytest.param(
  722. ComponentNestedVar.create(list_of_list_of_list=[[[f"foo{TEST_VAR}bar"]]]),
  723. [FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST],
  724. id="fstring-list_of_list_of_list",
  725. ),
  726. pytest.param(
  727. ComponentNestedVar.create(list_of_dict=[{"a": TEST_VAR}]),
  728. [TEST_VAR_LIST_OF_DICT],
  729. id="direct-list_of_dict",
  730. ),
  731. pytest.param(
  732. ComponentNestedVar.create(list_of_dict=[{"a": f"foo{TEST_VAR}bar"}]),
  733. [FORMATTED_TEST_VAR_LIST_OF_DICT],
  734. id="fstring-list_of_dict",
  735. ),
  736. ),
  737. )
  738. def test_get_vars(component, exp_vars):
  739. comp_vars = sorted(component._get_vars(), key=lambda v: v._var_name)
  740. assert len(comp_vars) == len(exp_vars)
  741. for comp_var, exp_var in zip(
  742. comp_vars,
  743. sorted(exp_vars, key=lambda v: v._var_name),
  744. ):
  745. assert comp_var.equals(exp_var)
  746. def test_instantiate_all_components():
  747. """Test that all components can be instantiated."""
  748. # These components all have required arguments and cannot be trivially instantiated.
  749. untested_components = {
  750. "Card",
  751. "Cond",
  752. "DebounceInput",
  753. "Foreach",
  754. "FormControl",
  755. "Html",
  756. "Icon",
  757. "Match",
  758. "Markdown",
  759. "MultiSelect",
  760. "Option",
  761. "Popover",
  762. "Radio",
  763. "Script",
  764. "Tag",
  765. "Tfoot",
  766. "Thead",
  767. }
  768. for component_name in rx._ALL_COMPONENTS: # type: ignore
  769. if component_name in untested_components:
  770. continue
  771. component = getattr(rx, component_name)
  772. if isinstance(component, type) and issubclass(component, Component):
  773. component.create()
  774. class InvalidParentComponent(Component):
  775. """Invalid Parent Component."""
  776. ...
  777. class ValidComponent1(Component):
  778. """Test valid component."""
  779. _valid_children = ["ValidComponent2"]
  780. class ValidComponent2(Component):
  781. """Test valid component."""
  782. ...
  783. class ValidComponent3(Component):
  784. """Test valid component."""
  785. _valid_parents = ["ValidComponent2"]
  786. class ValidComponent4(Component):
  787. """Test valid component."""
  788. _invalid_children = ["InvalidComponent"]
  789. class InvalidComponent(Component):
  790. """Test invalid component."""
  791. ...
  792. valid_component1 = ValidComponent1.create
  793. valid_component2 = ValidComponent2.create
  794. invalid_component = InvalidComponent.create
  795. valid_component3 = ValidComponent3.create
  796. invalid_parent = InvalidParentComponent.create
  797. valid_component4 = ValidComponent4.create
  798. def test_validate_valid_children():
  799. valid_component1(valid_component2())
  800. valid_component1(
  801. rx.fragment(valid_component2()),
  802. )
  803. valid_component1(
  804. rx.fragment(
  805. rx.fragment(
  806. rx.fragment(valid_component2()),
  807. ),
  808. ),
  809. )
  810. valid_component1(
  811. rx.cond( # type: ignore
  812. True,
  813. rx.fragment(valid_component2()),
  814. rx.fragment(
  815. rx.foreach(Var.create([1, 2, 3]), lambda x: valid_component2(x)) # type: ignore
  816. ),
  817. )
  818. )
  819. valid_component1(
  820. rx.cond(
  821. True,
  822. valid_component2(),
  823. rx.fragment(
  824. rx.match(
  825. "condition",
  826. ("first", valid_component2()),
  827. rx.fragment(valid_component2(rx.text("default"))),
  828. )
  829. ),
  830. )
  831. )
  832. valid_component1(
  833. rx.match(
  834. "condition",
  835. ("first", valid_component2()),
  836. ("second", "third", rx.fragment(valid_component2())),
  837. (
  838. "fourth",
  839. rx.cond(True, valid_component2(), rx.fragment(valid_component2())),
  840. ),
  841. (
  842. "fifth",
  843. rx.match(
  844. "nested_condition",
  845. ("nested_first", valid_component2()),
  846. rx.fragment(valid_component2()),
  847. ),
  848. valid_component2(),
  849. ),
  850. )
  851. )
  852. def test_validate_valid_parents():
  853. valid_component2(valid_component3())
  854. valid_component2(
  855. rx.fragment(valid_component3()),
  856. )
  857. valid_component1(
  858. rx.fragment(
  859. valid_component2(
  860. rx.fragment(valid_component3()),
  861. ),
  862. ),
  863. )
  864. valid_component2(
  865. rx.cond( # type: ignore
  866. True,
  867. rx.fragment(valid_component3()),
  868. rx.fragment(
  869. rx.foreach(
  870. Var.create([1, 2, 3]), # type: ignore
  871. lambda x: valid_component2(valid_component3(x)),
  872. )
  873. ),
  874. )
  875. )
  876. valid_component2(
  877. rx.cond(
  878. True,
  879. valid_component3(),
  880. rx.fragment(
  881. rx.match(
  882. "condition",
  883. ("first", valid_component3()),
  884. rx.fragment(valid_component3(rx.text("default"))),
  885. )
  886. ),
  887. )
  888. )
  889. valid_component2(
  890. rx.match(
  891. "condition",
  892. ("first", valid_component3()),
  893. ("second", "third", rx.fragment(valid_component3())),
  894. (
  895. "fourth",
  896. rx.cond(True, valid_component3(), rx.fragment(valid_component3())),
  897. ),
  898. (
  899. "fifth",
  900. rx.match(
  901. "nested_condition",
  902. ("nested_first", valid_component3()),
  903. rx.fragment(valid_component3()),
  904. ),
  905. valid_component3(),
  906. ),
  907. )
  908. )
  909. def test_validate_invalid_children():
  910. with pytest.raises(ValueError):
  911. valid_component4(invalid_component())
  912. with pytest.raises(ValueError):
  913. valid_component4(
  914. rx.fragment(invalid_component()),
  915. )
  916. with pytest.raises(ValueError):
  917. valid_component2(
  918. rx.fragment(
  919. valid_component4(
  920. rx.fragment(invalid_component()),
  921. ),
  922. ),
  923. )
  924. with pytest.raises(ValueError):
  925. valid_component4(
  926. rx.cond( # type: ignore
  927. True,
  928. rx.fragment(invalid_component()),
  929. rx.fragment(
  930. rx.foreach(Var.create([1, 2, 3]), lambda x: invalid_component(x)) # type: ignore
  931. ),
  932. )
  933. )
  934. with pytest.raises(ValueError):
  935. valid_component4(
  936. rx.cond(
  937. True,
  938. invalid_component(),
  939. rx.fragment(
  940. rx.match(
  941. "condition",
  942. ("first", invalid_component()),
  943. rx.fragment(invalid_component(rx.text("default"))),
  944. )
  945. ),
  946. )
  947. )
  948. with pytest.raises(ValueError):
  949. valid_component4(
  950. rx.match(
  951. "condition",
  952. ("first", invalid_component()),
  953. ("second", "third", rx.fragment(invalid_component())),
  954. (
  955. "fourth",
  956. rx.cond(True, invalid_component(), rx.fragment(valid_component2())),
  957. ),
  958. (
  959. "fifth",
  960. rx.match(
  961. "nested_condition",
  962. ("nested_first", invalid_component()),
  963. rx.fragment(invalid_component()),
  964. ),
  965. invalid_component(),
  966. ),
  967. )
  968. )
  969. def test_rename_props():
  970. """Test that _rename_props works and is inherited."""
  971. class C1(Component):
  972. tag = "C1"
  973. prop1: Var[str]
  974. prop2: Var[str]
  975. _rename_props = {"prop1": "renamed_prop1", "prop2": "renamed_prop2"}
  976. class C2(C1):
  977. tag = "C2"
  978. prop3: Var[str]
  979. _rename_props = {"prop2": "subclass_prop2", "prop3": "renamed_prop3"}
  980. c1 = C1.create(prop1="prop1_1", prop2="prop2_1")
  981. rendered_c1 = c1.render()
  982. assert "renamed_prop1={`prop1_1`}" in rendered_c1["props"]
  983. assert "renamed_prop2={`prop2_1`}" in rendered_c1["props"]
  984. c2 = C2.create(prop1="prop1_2", prop2="prop2_2", prop3="prop3_2")
  985. rendered_c2 = c2.render()
  986. assert "renamed_prop1={`prop1_2`}" in rendered_c2["props"]
  987. assert "subclass_prop2={`prop2_2`}" in rendered_c2["props"]
  988. assert "renamed_prop3={`prop3_2`}" in rendered_c2["props"]
  989. def test_deprecated_props(capsys):
  990. """Assert that deprecated underscore suffix props are translated.
  991. Args:
  992. capsys: Pytest fixture for capturing stdout and stderr.
  993. """
  994. class C1(Component):
  995. tag = "C1"
  996. type: Var[str]
  997. min: Var[str]
  998. max: Var[str]
  999. # No warnings are emitted when using the new prop names.
  1000. c1_1 = C1.create(type="type1", min="min1", max="max1")
  1001. out_err = capsys.readouterr()
  1002. assert not out_err.err
  1003. assert not out_err.out
  1004. c1_1_render = c1_1.render()
  1005. assert "type={`type1`}" in c1_1_render["props"]
  1006. assert "min={`min1`}" in c1_1_render["props"]
  1007. assert "max={`max1`}" in c1_1_render["props"]
  1008. # Deprecation warning is emitted with underscore suffix,
  1009. # but the component still works.
  1010. c1_2 = C1.create(type_="type2", min_="min2", max_="max2")
  1011. out_err = capsys.readouterr()
  1012. assert out_err.out.count("DeprecationWarning:") == 3
  1013. assert not out_err.err
  1014. c1_2_render = c1_2.render()
  1015. assert "type={`type2`}" in c1_2_render["props"]
  1016. assert "min={`min2`}" in c1_2_render["props"]
  1017. assert "max={`max2`}" in c1_2_render["props"]
  1018. class C2(Component):
  1019. tag = "C2"
  1020. type_: Var[str]
  1021. min_: Var[str]
  1022. max_: Var[str]
  1023. # No warnings are emitted if the actual prop has an underscore suffix
  1024. c2_1 = C2.create(type_="type1", min_="min1", max_="max1")
  1025. out_err = capsys.readouterr()
  1026. assert not out_err.err
  1027. assert not out_err.out
  1028. c2_1_render = c2_1.render()
  1029. assert "type={`type1`}" in c2_1_render["props"]
  1030. assert "min={`min1`}" in c2_1_render["props"]
  1031. assert "max={`max1`}" in c2_1_render["props"]