test_component.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  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. return TestComponent5
  100. @pytest.fixture
  101. def component6() -> Type[Component]:
  102. """A test component.
  103. Returns:
  104. A test component.
  105. """
  106. class TestComponent6(Component):
  107. tag = "RandomComponent"
  108. _invalid_children: List[str] = ["Text"]
  109. return TestComponent6
  110. @pytest.fixture
  111. def component7() -> Type[Component]:
  112. """A test component.
  113. Returns:
  114. A test component.
  115. """
  116. class TestComponent7(Component):
  117. tag = "RandomComponent"
  118. _valid_children: List[str] = ["Text"]
  119. return TestComponent7
  120. @pytest.fixture
  121. def on_click1() -> EventHandler:
  122. """A sample on click function.
  123. Returns:
  124. A sample on click function.
  125. """
  126. def on_click1():
  127. pass
  128. return EventHandler(fn=on_click1)
  129. @pytest.fixture
  130. def on_click2() -> EventHandler:
  131. """A sample on click function.
  132. Returns:
  133. A sample on click function.
  134. """
  135. def on_click2():
  136. pass
  137. return EventHandler(fn=on_click2)
  138. @pytest.fixture
  139. def my_component():
  140. """A test component function.
  141. Returns:
  142. A test component function.
  143. """
  144. def my_component(prop1: Var[str], prop2: Var[int]):
  145. return Box.create(prop1, prop2)
  146. return my_component
  147. def test_set_style_attrs(component1):
  148. """Test that style attributes are set in the dict.
  149. Args:
  150. component1: A test component.
  151. """
  152. component = component1(color="white", text_align="center")
  153. assert component.style["color"] == "white"
  154. assert component.style["textAlign"] == "center"
  155. def test_custom_attrs(component1):
  156. """Test that custom attributes are set in the dict.
  157. Args:
  158. component1: A test component.
  159. """
  160. component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
  161. assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
  162. def test_create_component(component1):
  163. """Test that the component is created correctly.
  164. Args:
  165. component1: A test component.
  166. """
  167. children = [component1() for _ in range(3)]
  168. attrs = {"color": "white", "text_align": "center"}
  169. c = component1.create(*children, **attrs)
  170. assert isinstance(c, component1)
  171. assert c.children == children
  172. assert c.style == {"color": "white", "textAlign": "center"}
  173. def test_add_style(component1, component2):
  174. """Test adding a style to a component.
  175. Args:
  176. component1: A test component.
  177. component2: A test component.
  178. """
  179. style = {
  180. component1: Style({"color": "white"}),
  181. component2: Style({"color": "black"}),
  182. }
  183. c1 = component1().add_style(style) # type: ignore
  184. c2 = component2().add_style(style) # type: ignore
  185. assert c1.style["color"] == "white"
  186. assert c2.style["color"] == "black"
  187. def test_get_imports(component1, component2):
  188. """Test getting the imports of a component.
  189. Args:
  190. component1: A test component.
  191. component2: A test component.
  192. """
  193. c1 = component1.create()
  194. c2 = component2.create(c1)
  195. assert c1.get_imports() == {"react": [ImportVar(tag="Component")]}
  196. assert c2.get_imports() == {
  197. "react-redux": [ImportVar(tag="connect")],
  198. "react": [ImportVar(tag="Component")],
  199. }
  200. def test_get_custom_code(component1, component2):
  201. """Test getting the custom code of a component.
  202. Args:
  203. component1: A test component.
  204. component2: A test component.
  205. """
  206. # Check that the code gets compiled correctly.
  207. c1 = component1.create()
  208. c2 = component2.create()
  209. assert c1.get_custom_code() == {"console.log('component1')"}
  210. assert c2.get_custom_code() == {"console.log('component2')"}
  211. # Check that nesting components compiles both codes.
  212. c1 = component1.create(c2)
  213. assert c1.get_custom_code() == {
  214. "console.log('component1')",
  215. "console.log('component2')",
  216. }
  217. # Check that code is not duplicated.
  218. c1 = component1.create(c2, c2, c1, c1)
  219. assert c1.get_custom_code() == {
  220. "console.log('component1')",
  221. "console.log('component2')",
  222. }
  223. def test_get_props(component1, component2):
  224. """Test that the props are set correctly.
  225. Args:
  226. component1: A test component.
  227. component2: A test component.
  228. """
  229. assert component1.get_props() == {"text", "number"}
  230. assert component2.get_props() == {"arr"}
  231. @pytest.mark.parametrize(
  232. "text,number",
  233. [
  234. ("", 0),
  235. ("test", 1),
  236. ("hi", -13),
  237. ],
  238. )
  239. def test_valid_props(component1, text: str, number: int):
  240. """Test that we can construct a component with valid props.
  241. Args:
  242. component1: A test component.
  243. text: A test string.
  244. number: A test number.
  245. """
  246. c = component1.create(text=text, number=number)
  247. assert c.text._decode() == text
  248. assert c.number._decode() == number
  249. @pytest.mark.parametrize(
  250. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  251. )
  252. def test_invalid_prop_type(component1, text: str, number: int):
  253. """Test that an invalid prop type raises an error.
  254. Args:
  255. component1: A test component.
  256. text: A test string.
  257. number: A test number.
  258. """
  259. # Check that
  260. with pytest.raises(TypeError):
  261. component1.create(text=text, number=number)
  262. def test_var_props(component1, test_state):
  263. """Test that we can set a Var prop.
  264. Args:
  265. component1: A test component.
  266. test_state: A test state.
  267. """
  268. c1 = component1.create(text="hello", number=test_state.num)
  269. assert c1.number.equals(test_state.num)
  270. def test_get_event_triggers(component1, component2):
  271. """Test that we can get the triggers of a component.
  272. Args:
  273. component1: A test component.
  274. component2: A test component.
  275. """
  276. default_triggers = {
  277. EventTriggers.ON_FOCUS,
  278. EventTriggers.ON_BLUR,
  279. EventTriggers.ON_CLICK,
  280. EventTriggers.ON_CONTEXT_MENU,
  281. EventTriggers.ON_DOUBLE_CLICK,
  282. EventTriggers.ON_MOUSE_DOWN,
  283. EventTriggers.ON_MOUSE_ENTER,
  284. EventTriggers.ON_MOUSE_LEAVE,
  285. EventTriggers.ON_MOUSE_MOVE,
  286. EventTriggers.ON_MOUSE_OUT,
  287. EventTriggers.ON_MOUSE_OVER,
  288. EventTriggers.ON_MOUSE_UP,
  289. EventTriggers.ON_SCROLL,
  290. EventTriggers.ON_MOUNT,
  291. EventTriggers.ON_UNMOUNT,
  292. }
  293. assert set(component1().get_event_triggers().keys()) == default_triggers
  294. assert (
  295. component2().get_event_triggers().keys()
  296. == {"on_open", "on_close"} | default_triggers
  297. )
  298. class C1State(BaseState):
  299. """State for testing C1 component."""
  300. def mock_handler(self, _e, _bravo, _charlie):
  301. """Mock handler."""
  302. pass
  303. def test_component_event_trigger_arbitrary_args():
  304. """Test that we can define arbitrary types for the args of an event trigger."""
  305. class Obj(Base):
  306. custom: int = 0
  307. def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj):
  308. return [_e.target.value, bravo["nested"], charlie.custom + 42]
  309. class C1(Component):
  310. library = "/local"
  311. tag = "C1"
  312. def get_event_triggers(self) -> Dict[str, Any]:
  313. return {
  314. **super().get_event_triggers(),
  315. "on_foo": on_foo_spec,
  316. }
  317. comp = C1.create(on_foo=C1State.mock_handler)
  318. assert comp.render()["props"][0] == (
  319. "onFoo={(__e,_alpha,_bravo,_charlie) => addEvents("
  320. '[Event("c1_state.mock_handler", {_e:__e.target.value,_bravo:_bravo["nested"],_charlie:(_charlie.custom + 42)})], '
  321. "(__e,_alpha,_bravo,_charlie), {})}"
  322. )
  323. def test_create_custom_component(my_component):
  324. """Test that we can create a custom component.
  325. Args:
  326. my_component: A test custom component.
  327. """
  328. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  329. assert component.tag == "MyComponent"
  330. assert component.get_props() == set()
  331. assert component.get_custom_components() == {component}
  332. def test_custom_component_hash(my_component):
  333. """Test that the hash of a custom component is correct.
  334. Args:
  335. my_component: A test custom component.
  336. """
  337. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  338. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  339. assert {component1, component2} == {component1}
  340. def test_custom_component_wrapper():
  341. """Test that the wrapper of a custom component is correct."""
  342. @custom_component
  343. def my_component(width: Var[int], color: Var[str]):
  344. return rx.box(
  345. width=width,
  346. color=color,
  347. )
  348. ccomponent = my_component(
  349. rx.text("child"), width=Var.create(1), color=Var.create("red")
  350. )
  351. assert isinstance(ccomponent, CustomComponent)
  352. assert len(ccomponent.children) == 1
  353. assert isinstance(ccomponent.children[0], rx.Text)
  354. component = ccomponent.get_component(ccomponent)
  355. assert isinstance(component, Box)
  356. def test_invalid_event_handler_args(component2, test_state):
  357. """Test that an invalid event handler raises an error.
  358. Args:
  359. component2: A test component.
  360. test_state: A test state.
  361. """
  362. # Uncontrolled event handlers should not take args.
  363. # This is okay.
  364. component2.create(on_click=test_state.do_something)
  365. # This is not okay.
  366. with pytest.raises(ValueError):
  367. component2.create(on_click=test_state.do_something_arg)
  368. component2.create(on_open=test_state.do_something)
  369. component2.create(
  370. on_open=[test_state.do_something_arg, test_state.do_something]
  371. )
  372. # However lambdas are okay.
  373. component2.create(on_click=lambda: test_state.do_something_arg(1))
  374. component2.create(
  375. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  376. )
  377. component2.create(
  378. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  379. )
  380. # Controlled event handlers should take args.
  381. # This is okay.
  382. component2.create(on_open=test_state.do_something_arg)
  383. def test_get_hooks_nested(component1, component2, component3):
  384. """Test that a component returns hooks from child components.
  385. Args:
  386. component1: test component.
  387. component2: another component.
  388. component3: component with hooks defined.
  389. """
  390. c = component1.create(
  391. component2.create(arr=[]),
  392. component3.create(),
  393. component3.create(),
  394. component3.create(),
  395. text="a",
  396. number=1,
  397. )
  398. assert c.get_hooks() == component3().get_hooks()
  399. def test_get_hooks_nested2(component3, component4):
  400. """Test that a component returns both when parent and child have hooks.
  401. Args:
  402. component3: component with hooks defined.
  403. component4: component with different hooks defined.
  404. """
  405. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  406. assert component3.create(component4.create()).get_hooks() == exp_hooks
  407. assert component4.create(component3.create()).get_hooks() == exp_hooks
  408. assert (
  409. component4.create(
  410. component3.create(),
  411. component4.create(),
  412. component3.create(),
  413. ).get_hooks()
  414. == exp_hooks
  415. )
  416. @pytest.mark.parametrize("fixture", ["component5", "component6"])
  417. def test_unsupported_child_components(fixture, request):
  418. """Test that a value error is raised when an unsupported component (a child component found in the
  419. component's invalid children list) is provided as a child.
  420. Args:
  421. fixture: the test component as a fixture.
  422. request: Pytest request.
  423. """
  424. component = request.getfixturevalue(fixture)
  425. with pytest.raises(ValueError) as err:
  426. comp = component.create(rx.text("testing component"))
  427. comp.render()
  428. assert (
  429. err.value.args[0]
  430. == f"The component `{component.__name__}` cannot have `Text` as a child component"
  431. )
  432. @pytest.mark.parametrize("fixture", ["component5", "component7"])
  433. def test_component_with_only_valid_children(fixture, request):
  434. """Test that a value error is raised when an unsupported component (a child component not found in the
  435. component's valid 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.box("testing component"))
  443. comp.render()
  444. assert (
  445. err.value.args[0]
  446. == f"The component `{component.__name__}` only allows the components: `Text` as children. "
  447. f"Got `Box` instead."
  448. )
  449. @pytest.mark.parametrize(
  450. "component,rendered",
  451. [
  452. (rx.text("hi"), "<Text>\n {`hi`}\n</Text>"),
  453. (
  454. rx.box(rx.heading("test", size="md")),
  455. "<Box>\n <Heading size={`md`}>\n {`test`}\n</Heading>\n</Box>",
  456. ),
  457. ],
  458. )
  459. def test_format_component(component, rendered):
  460. """Test that a component is formatted correctly.
  461. Args:
  462. component: The component to format.
  463. rendered: The expected rendered component.
  464. """
  465. assert str(component) == rendered
  466. def test_stateful_component(test_state):
  467. """Test that a stateful component is created correctly.
  468. Args:
  469. test_state: A test state.
  470. """
  471. text_component = rx.text(test_state.num)
  472. stateful_component = StatefulComponent.compile_from(text_component)
  473. assert isinstance(stateful_component, StatefulComponent)
  474. assert stateful_component.tag is not None
  475. assert stateful_component.tag.startswith("Text_")
  476. assert stateful_component.references == 1
  477. sc2 = StatefulComponent.compile_from(rx.text(test_state.num))
  478. assert isinstance(sc2, StatefulComponent)
  479. assert stateful_component.references == 2
  480. assert sc2.references == 2
  481. def test_stateful_component_memoize_event_trigger(test_state):
  482. """Test that a stateful component is created correctly with events.
  483. Args:
  484. test_state: A test state.
  485. """
  486. button_component = rx.button("Click me", on_click=test_state.do_something)
  487. stateful_component = StatefulComponent.compile_from(button_component)
  488. assert isinstance(stateful_component, StatefulComponent)
  489. # No event trigger? No StatefulComponent
  490. assert not isinstance(
  491. StatefulComponent.compile_from(rx.button("Click me")), StatefulComponent
  492. )
  493. def test_stateful_banner():
  494. """Test that a stateful component is created correctly with events."""
  495. connection_modal_component = rx.connection_modal()
  496. stateful_component = StatefulComponent.compile_from(connection_modal_component)
  497. assert isinstance(stateful_component, StatefulComponent)
  498. TEST_VAR = Var.create_safe("test")._replace(
  499. merge_var_data=VarData(
  500. hooks={"useTest"}, imports={"test": {ImportVar(tag="test")}}, state="Test"
  501. )
  502. )
  503. FORMATTED_TEST_VAR = Var.create(f"foo{TEST_VAR}bar")
  504. STYLE_VAR = TEST_VAR._replace(_var_name="style", _var_is_local=False)
  505. EVENT_CHAIN_VAR = TEST_VAR._replace(_var_type=EventChain)
  506. ARG_VAR = Var.create("arg")
  507. TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": "test"}})._replace(
  508. merge_var_data=TEST_VAR._var_data
  509. )
  510. FORMATTED_TEST_VAR_DICT_OF_DICT = Var.create_safe({"a": {"b": f"footestbar"}})._replace(
  511. merge_var_data=TEST_VAR._var_data
  512. )
  513. TEST_VAR_LIST_OF_LIST = Var.create_safe([["test"]])._replace(
  514. merge_var_data=TEST_VAR._var_data
  515. )
  516. FORMATTED_TEST_VAR_LIST_OF_LIST = Var.create_safe([["footestbar"]])._replace(
  517. merge_var_data=TEST_VAR._var_data
  518. )
  519. TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["test"]]])._replace(
  520. merge_var_data=TEST_VAR._var_data
  521. )
  522. FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST = Var.create_safe([[["footestbar"]]])._replace(
  523. merge_var_data=TEST_VAR._var_data
  524. )
  525. TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "test"}])._replace(
  526. merge_var_data=TEST_VAR._var_data
  527. )
  528. FORMATTED_TEST_VAR_LIST_OF_DICT = Var.create_safe([{"a": "footestbar"}])._replace(
  529. merge_var_data=TEST_VAR._var_data
  530. )
  531. class ComponentNestedVar(Component):
  532. """A component with nested Var types."""
  533. dict_of_dict: Var[Dict[str, Dict[str, str]]]
  534. list_of_list: Var[List[List[str]]]
  535. list_of_list_of_list: Var[List[List[List[str]]]]
  536. list_of_dict: Var[List[Dict[str, str]]]
  537. class EventState(rx.State):
  538. """State for testing event handlers with _get_vars."""
  539. v: int = 42
  540. def handler(self):
  541. """A handler that does nothing."""
  542. def handler2(self, arg):
  543. """A handler that takes an arg.
  544. Args:
  545. arg: An arg.
  546. """
  547. @pytest.mark.parametrize(
  548. ("component", "exp_vars"),
  549. (
  550. pytest.param(
  551. Bare.create(TEST_VAR),
  552. [TEST_VAR],
  553. id="direct-bare",
  554. ),
  555. pytest.param(
  556. Bare.create(f"foo{TEST_VAR}bar"),
  557. [FORMATTED_TEST_VAR],
  558. id="fstring-bare",
  559. ),
  560. pytest.param(
  561. rx.text(as_=TEST_VAR),
  562. [TEST_VAR],
  563. id="direct-prop",
  564. ),
  565. pytest.param(
  566. rx.text(as_=f"foo{TEST_VAR}bar"),
  567. [FORMATTED_TEST_VAR],
  568. id="fstring-prop",
  569. ),
  570. pytest.param(
  571. rx.fragment(id=TEST_VAR),
  572. [TEST_VAR],
  573. id="direct-id",
  574. ),
  575. pytest.param(
  576. rx.fragment(id=f"foo{TEST_VAR}bar"),
  577. [FORMATTED_TEST_VAR],
  578. id="fstring-id",
  579. ),
  580. pytest.param(
  581. rx.fragment(key=TEST_VAR),
  582. [TEST_VAR],
  583. id="direct-key",
  584. ),
  585. pytest.param(
  586. rx.fragment(key=f"foo{TEST_VAR}bar"),
  587. [FORMATTED_TEST_VAR],
  588. id="fstring-key",
  589. ),
  590. pytest.param(
  591. rx.fragment(class_name=TEST_VAR),
  592. [TEST_VAR],
  593. id="direct-class_name",
  594. ),
  595. pytest.param(
  596. rx.fragment(class_name=f"foo{TEST_VAR}bar"),
  597. [FORMATTED_TEST_VAR],
  598. id="fstring-class_name",
  599. ),
  600. pytest.param(
  601. rx.fragment(special_props={TEST_VAR}),
  602. [TEST_VAR],
  603. id="direct-special_props",
  604. ),
  605. pytest.param(
  606. rx.fragment(special_props={Var.create(f"foo{TEST_VAR}bar")}),
  607. [FORMATTED_TEST_VAR],
  608. id="fstring-special_props",
  609. ),
  610. pytest.param(
  611. # custom_attrs cannot accept a Var directly as a value
  612. rx.fragment(custom_attrs={"href": f"{TEST_VAR}"}),
  613. [TEST_VAR],
  614. id="fstring-custom_attrs-nofmt",
  615. ),
  616. pytest.param(
  617. rx.fragment(custom_attrs={"href": f"foo{TEST_VAR}bar"}),
  618. [FORMATTED_TEST_VAR],
  619. id="fstring-custom_attrs",
  620. ),
  621. pytest.param(
  622. rx.fragment(background_color=TEST_VAR),
  623. [STYLE_VAR],
  624. id="direct-background_color",
  625. ),
  626. pytest.param(
  627. rx.fragment(background_color=f"foo{TEST_VAR}bar"),
  628. [STYLE_VAR],
  629. id="fstring-background_color",
  630. ),
  631. pytest.param(
  632. rx.fragment(style={"background_color": TEST_VAR}), # type: ignore
  633. [STYLE_VAR],
  634. id="direct-style-background_color",
  635. ),
  636. pytest.param(
  637. rx.fragment(style={"background_color": f"foo{TEST_VAR}bar"}), # type: ignore
  638. [STYLE_VAR],
  639. id="fstring-style-background_color",
  640. ),
  641. pytest.param(
  642. rx.fragment(on_click=EVENT_CHAIN_VAR), # type: ignore
  643. [EVENT_CHAIN_VAR],
  644. id="direct-event-chain",
  645. ),
  646. pytest.param(
  647. rx.fragment(on_click=EventState.handler),
  648. [],
  649. id="direct-event-handler",
  650. ),
  651. pytest.param(
  652. rx.fragment(on_click=EventState.handler2(TEST_VAR)), # type: ignore
  653. [ARG_VAR, TEST_VAR],
  654. id="direct-event-handler-arg",
  655. ),
  656. pytest.param(
  657. rx.fragment(on_click=EventState.handler2(EventState.v)), # type: ignore
  658. [ARG_VAR, EventState.v],
  659. id="direct-event-handler-arg2",
  660. ),
  661. pytest.param(
  662. rx.fragment(on_click=lambda: EventState.handler2(TEST_VAR)), # type: ignore
  663. [ARG_VAR, TEST_VAR],
  664. id="direct-event-handler-lambda",
  665. ),
  666. pytest.param(
  667. ComponentNestedVar.create(dict_of_dict={"a": {"b": TEST_VAR}}),
  668. [TEST_VAR_DICT_OF_DICT],
  669. id="direct-dict_of_dict",
  670. ),
  671. pytest.param(
  672. ComponentNestedVar.create(dict_of_dict={"a": {"b": f"foo{TEST_VAR}bar"}}),
  673. [FORMATTED_TEST_VAR_DICT_OF_DICT],
  674. id="fstring-dict_of_dict",
  675. ),
  676. pytest.param(
  677. ComponentNestedVar.create(list_of_list=[[TEST_VAR]]),
  678. [TEST_VAR_LIST_OF_LIST],
  679. id="direct-list_of_list",
  680. ),
  681. pytest.param(
  682. ComponentNestedVar.create(list_of_list=[[f"foo{TEST_VAR}bar"]]),
  683. [FORMATTED_TEST_VAR_LIST_OF_LIST],
  684. id="fstring-list_of_list",
  685. ),
  686. pytest.param(
  687. ComponentNestedVar.create(list_of_list_of_list=[[[TEST_VAR]]]),
  688. [TEST_VAR_LIST_OF_LIST_OF_LIST],
  689. id="direct-list_of_list_of_list",
  690. ),
  691. pytest.param(
  692. ComponentNestedVar.create(list_of_list_of_list=[[[f"foo{TEST_VAR}bar"]]]),
  693. [FORMATTED_TEST_VAR_LIST_OF_LIST_OF_LIST],
  694. id="fstring-list_of_list_of_list",
  695. ),
  696. pytest.param(
  697. ComponentNestedVar.create(list_of_dict=[{"a": TEST_VAR}]),
  698. [TEST_VAR_LIST_OF_DICT],
  699. id="direct-list_of_dict",
  700. ),
  701. pytest.param(
  702. ComponentNestedVar.create(list_of_dict=[{"a": f"foo{TEST_VAR}bar"}]),
  703. [FORMATTED_TEST_VAR_LIST_OF_DICT],
  704. id="fstring-list_of_dict",
  705. ),
  706. ),
  707. )
  708. def test_get_vars(component, exp_vars):
  709. comp_vars = sorted(component._get_vars(), key=lambda v: v._var_name)
  710. assert len(comp_vars) == len(exp_vars)
  711. for comp_var, exp_var in zip(
  712. comp_vars,
  713. sorted(exp_vars, key=lambda v: v._var_name),
  714. ):
  715. assert comp_var.equals(exp_var)
  716. def test_instantiate_all_components():
  717. """Test that all components can be instantiated."""
  718. # These components all have required arguments and cannot be trivially instantiated.
  719. untested_components = {
  720. "Card",
  721. "Cond",
  722. "DebounceInput",
  723. "Foreach",
  724. "FormControl",
  725. "Html",
  726. "Icon",
  727. "Markdown",
  728. "MultiSelect",
  729. "Option",
  730. "Popover",
  731. "Radio",
  732. "Script",
  733. "Tag",
  734. "Tfoot",
  735. "Thead",
  736. }
  737. for component_name in rx._ALL_COMPONENTS: # type: ignore
  738. if component_name in untested_components:
  739. continue
  740. component = getattr(rx, component_name)
  741. if isinstance(component, type) and issubclass(component, Component):
  742. component.create()