test_component.py 45 KB

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