test_component.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  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.component import Component, CustomComponent, custom_component
  6. from reflex.components.layout.box import Box
  7. from reflex.constants import EventTriggers
  8. from reflex.event import EventHandler
  9. from reflex.state import State
  10. from reflex.style import Style
  11. from reflex.utils import imports
  12. from reflex.vars import ImportVar, Var
  13. @pytest.fixture
  14. def test_state():
  15. class TestState(State):
  16. num: int
  17. def do_something(self):
  18. pass
  19. def do_something_arg(self, arg):
  20. pass
  21. return TestState
  22. @pytest.fixture
  23. def component1() -> Type[Component]:
  24. """A test component.
  25. Returns:
  26. A test component.
  27. """
  28. class TestComponent1(Component):
  29. # A test string prop.
  30. text: Var[str]
  31. # A test number prop.
  32. number: Var[int]
  33. def _get_imports(self) -> imports.ImportDict:
  34. return {"react": [ImportVar(tag="Component")]}
  35. def _get_custom_code(self) -> str:
  36. return "console.log('component1')"
  37. return TestComponent1
  38. @pytest.fixture
  39. def component2() -> Type[Component]:
  40. """A test component.
  41. Returns:
  42. A test component.
  43. """
  44. class TestComponent2(Component):
  45. # A test list prop.
  46. arr: Var[List[str]]
  47. def get_event_triggers(self) -> Dict[str, Any]:
  48. """Test controlled triggers.
  49. Returns:
  50. Test controlled triggers.
  51. """
  52. return {
  53. **super().get_event_triggers(),
  54. "on_open": lambda e0: [e0],
  55. "on_close": lambda e0: [e0],
  56. }
  57. def _get_imports(self) -> imports.ImportDict:
  58. return {"react-redux": [ImportVar(tag="connect")]}
  59. def _get_custom_code(self) -> str:
  60. return "console.log('component2')"
  61. return TestComponent2
  62. @pytest.fixture
  63. def component3() -> Type[Component]:
  64. """A test component with hook defined.
  65. Returns:
  66. A test component.
  67. """
  68. class TestComponent3(Component):
  69. def _get_hooks(self) -> str:
  70. return "const a = () => true"
  71. return TestComponent3
  72. @pytest.fixture
  73. def component4() -> Type[Component]:
  74. """A test component with hook defined.
  75. Returns:
  76. A test component.
  77. """
  78. class TestComponent4(Component):
  79. def _get_hooks(self) -> str:
  80. return "const b = () => false"
  81. return TestComponent4
  82. @pytest.fixture
  83. def component5() -> Type[Component]:
  84. """A test component.
  85. Returns:
  86. A test component.
  87. """
  88. class TestComponent5(Component):
  89. tag = "RandomComponent"
  90. _invalid_children: List[str] = ["Text"]
  91. _valid_children: List[str] = ["Text"]
  92. return TestComponent5
  93. @pytest.fixture
  94. def component6() -> Type[Component]:
  95. """A test component.
  96. Returns:
  97. A test component.
  98. """
  99. class TestComponent6(Component):
  100. tag = "RandomComponent"
  101. _invalid_children: List[str] = ["Text"]
  102. return TestComponent6
  103. @pytest.fixture
  104. def component7() -> Type[Component]:
  105. """A test component.
  106. Returns:
  107. A test component.
  108. """
  109. class TestComponent7(Component):
  110. tag = "RandomComponent"
  111. _valid_children: List[str] = ["Text"]
  112. return TestComponent7
  113. @pytest.fixture
  114. def on_click1() -> EventHandler:
  115. """A sample on click function.
  116. Returns:
  117. A sample on click function.
  118. """
  119. def on_click1():
  120. pass
  121. return EventHandler(fn=on_click1)
  122. @pytest.fixture
  123. def on_click2() -> EventHandler:
  124. """A sample on click function.
  125. Returns:
  126. A sample on click function.
  127. """
  128. def on_click2():
  129. pass
  130. return EventHandler(fn=on_click2)
  131. @pytest.fixture
  132. def my_component():
  133. """A test component function.
  134. Returns:
  135. A test component function.
  136. """
  137. def my_component(prop1: Var[str], prop2: Var[int]):
  138. return Box.create(prop1, prop2)
  139. return my_component
  140. def test_set_style_attrs(component1):
  141. """Test that style attributes are set in the dict.
  142. Args:
  143. component1: A test component.
  144. """
  145. component = component1(color="white", text_align="center")
  146. assert component.style["color"] == "white"
  147. assert component.style["textAlign"] == "center"
  148. def test_custom_attrs(component1):
  149. """Test that custom attributes are set in the dict.
  150. Args:
  151. component1: A test component.
  152. """
  153. component = component1(custom_attrs={"attr1": "1", "attr2": "attr2"})
  154. assert component.custom_attrs == {"attr1": "1", "attr2": "attr2"}
  155. def test_create_component(component1):
  156. """Test that the component is created correctly.
  157. Args:
  158. component1: A test component.
  159. """
  160. children = [component1() for _ in range(3)]
  161. attrs = {"color": "white", "text_align": "center"}
  162. c = component1.create(*children, **attrs)
  163. assert isinstance(c, component1)
  164. assert c.children == children
  165. assert c.style == {"color": "white", "textAlign": "center"}
  166. def test_add_style(component1, component2):
  167. """Test adding a style to a component.
  168. Args:
  169. component1: A test component.
  170. component2: A test component.
  171. """
  172. style = {
  173. component1: Style({"color": "white"}),
  174. component2: Style({"color": "black"}),
  175. }
  176. c1 = component1().add_style(style) # type: ignore
  177. c2 = component2().add_style(style) # type: ignore
  178. assert c1.style["color"] == "white"
  179. assert c2.style["color"] == "black"
  180. def test_get_imports(component1, component2):
  181. """Test getting the imports of a component.
  182. Args:
  183. component1: A test component.
  184. component2: A test component.
  185. """
  186. c1 = component1.create()
  187. c2 = component2.create(c1)
  188. assert c1.get_imports() == {"react": [ImportVar(tag="Component")]}
  189. assert c2.get_imports() == {
  190. "react-redux": [ImportVar(tag="connect")],
  191. "react": [ImportVar(tag="Component")],
  192. }
  193. def test_get_custom_code(component1, component2):
  194. """Test getting the custom code of a component.
  195. Args:
  196. component1: A test component.
  197. component2: A test component.
  198. """
  199. # Check that the code gets compiled correctly.
  200. c1 = component1.create()
  201. c2 = component2.create()
  202. assert c1.get_custom_code() == {"console.log('component1')"}
  203. assert c2.get_custom_code() == {"console.log('component2')"}
  204. # Check that nesting components compiles both codes.
  205. c1 = component1.create(c2)
  206. assert c1.get_custom_code() == {
  207. "console.log('component1')",
  208. "console.log('component2')",
  209. }
  210. # Check that code is not duplicated.
  211. c1 = component1.create(c2, c2, c1, c1)
  212. assert c1.get_custom_code() == {
  213. "console.log('component1')",
  214. "console.log('component2')",
  215. }
  216. def test_get_props(component1, component2):
  217. """Test that the props are set correctly.
  218. Args:
  219. component1: A test component.
  220. component2: A test component.
  221. """
  222. assert component1.get_props() == {"text", "number"}
  223. assert component2.get_props() == {"arr"}
  224. @pytest.mark.parametrize(
  225. "text,number",
  226. [
  227. ("", 0),
  228. ("test", 1),
  229. ("hi", -13),
  230. ],
  231. )
  232. def test_valid_props(component1, text: str, number: int):
  233. """Test that we can construct a component with valid props.
  234. Args:
  235. component1: A test component.
  236. text: A test string.
  237. number: A test number.
  238. """
  239. c = component1.create(text=text, number=number)
  240. assert c.text._decode() == text
  241. assert c.number._decode() == number
  242. @pytest.mark.parametrize(
  243. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  244. )
  245. def test_invalid_prop_type(component1, text: str, number: int):
  246. """Test that an invalid prop type raises an error.
  247. Args:
  248. component1: A test component.
  249. text: A test string.
  250. number: A test number.
  251. """
  252. # Check that
  253. with pytest.raises(TypeError):
  254. component1.create(text=text, number=number)
  255. def test_var_props(component1, test_state):
  256. """Test that we can set a Var prop.
  257. Args:
  258. component1: A test component.
  259. test_state: A test state.
  260. """
  261. c1 = component1.create(text="hello", number=test_state.num)
  262. assert c1.number.equals(test_state.num)
  263. def test_get_event_triggers(component1, component2):
  264. """Test that we can get the triggers of a component.
  265. Args:
  266. component1: A test component.
  267. component2: A test component.
  268. """
  269. default_triggers = {
  270. EventTriggers.ON_FOCUS,
  271. EventTriggers.ON_BLUR,
  272. EventTriggers.ON_CLICK,
  273. EventTriggers.ON_CONTEXT_MENU,
  274. EventTriggers.ON_DOUBLE_CLICK,
  275. EventTriggers.ON_MOUSE_DOWN,
  276. EventTriggers.ON_MOUSE_ENTER,
  277. EventTriggers.ON_MOUSE_LEAVE,
  278. EventTriggers.ON_MOUSE_MOVE,
  279. EventTriggers.ON_MOUSE_OUT,
  280. EventTriggers.ON_MOUSE_OVER,
  281. EventTriggers.ON_MOUSE_UP,
  282. EventTriggers.ON_SCROLL,
  283. EventTriggers.ON_MOUNT,
  284. EventTriggers.ON_UNMOUNT,
  285. }
  286. assert set(component1().get_event_triggers().keys()) == default_triggers
  287. assert (
  288. component2().get_event_triggers().keys()
  289. == {"on_open", "on_close"} | default_triggers
  290. )
  291. class C1State(State):
  292. """State for testing C1 component."""
  293. def mock_handler(self, _e, _bravo, _charlie):
  294. """Mock handler."""
  295. pass
  296. def test_component_event_trigger_arbitrary_args():
  297. """Test that we can define arbitrary types for the args of an event trigger."""
  298. class Obj(Base):
  299. custom: int = 0
  300. def on_foo_spec(_e, alpha: str, bravo: Dict[str, Any], charlie: Obj):
  301. return [_e.target.value, bravo["nested"], charlie.custom + 42]
  302. class C1(Component):
  303. library = "/local"
  304. tag = "C1"
  305. def get_event_triggers(self) -> Dict[str, Any]:
  306. return {
  307. **super().get_event_triggers(),
  308. "on_foo": on_foo_spec,
  309. }
  310. comp = C1.create(on_foo=C1State.mock_handler)
  311. assert comp.render()["props"][0] == (
  312. "onFoo={(__e,_alpha,_bravo,_charlie) => addEvents("
  313. '[Event("c1_state.mock_handler", {_e:__e.target.value,_bravo:_bravo["nested"],_charlie:(_charlie.custom + 42)})], '
  314. "(__e,_alpha,_bravo,_charlie), {})}"
  315. )
  316. def test_create_custom_component(my_component):
  317. """Test that we can create a custom component.
  318. Args:
  319. my_component: A test custom component.
  320. """
  321. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  322. assert component.tag == "MyComponent"
  323. assert component.get_props() == set()
  324. assert component.get_custom_components() == {component}
  325. def test_custom_component_hash(my_component):
  326. """Test that the hash of a custom component is correct.
  327. Args:
  328. my_component: A test custom component.
  329. """
  330. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  331. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  332. assert {component1, component2} == {component1}
  333. def test_custom_component_wrapper():
  334. """Test that the wrapper of a custom component is correct."""
  335. @custom_component
  336. def my_component(width: Var[int], color: Var[str]):
  337. return rx.box(
  338. width=width,
  339. color=color,
  340. )
  341. ccomponent = my_component(
  342. rx.text("child"), width=Var.create(1), color=Var.create("red")
  343. )
  344. assert isinstance(ccomponent, CustomComponent)
  345. assert len(ccomponent.children) == 1
  346. assert isinstance(ccomponent.children[0], rx.Text)
  347. component = ccomponent.get_component(ccomponent)
  348. assert isinstance(component, Box)
  349. def test_invalid_event_handler_args(component2, test_state):
  350. """Test that an invalid event handler raises an error.
  351. Args:
  352. component2: A test component.
  353. test_state: A test state.
  354. """
  355. # Uncontrolled event handlers should not take args.
  356. # This is okay.
  357. component2.create(on_click=test_state.do_something)
  358. # This is not okay.
  359. with pytest.raises(ValueError):
  360. component2.create(on_click=test_state.do_something_arg)
  361. component2.create(on_open=test_state.do_something)
  362. component2.create(
  363. on_open=[test_state.do_something_arg, test_state.do_something]
  364. )
  365. # However lambdas are okay.
  366. component2.create(on_click=lambda: test_state.do_something_arg(1))
  367. component2.create(
  368. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  369. )
  370. component2.create(
  371. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  372. )
  373. # Controlled event handlers should take args.
  374. # This is okay.
  375. component2.create(on_open=test_state.do_something_arg)
  376. def test_get_hooks_nested(component1, component2, component3):
  377. """Test that a component returns hooks from child components.
  378. Args:
  379. component1: test component.
  380. component2: another component.
  381. component3: component with hooks defined.
  382. """
  383. c = component1.create(
  384. component2.create(arr=[]),
  385. component3.create(),
  386. component3.create(),
  387. component3.create(),
  388. text="a",
  389. number=1,
  390. )
  391. assert c.get_hooks() == component3().get_hooks()
  392. def test_get_hooks_nested2(component3, component4):
  393. """Test that a component returns both when parent and child have hooks.
  394. Args:
  395. component3: component with hooks defined.
  396. component4: component with different hooks defined.
  397. """
  398. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  399. assert component3.create(component4.create()).get_hooks() == exp_hooks
  400. assert component4.create(component3.create()).get_hooks() == exp_hooks
  401. assert (
  402. component4.create(
  403. component3.create(),
  404. component4.create(),
  405. component3.create(),
  406. ).get_hooks()
  407. == exp_hooks
  408. )
  409. @pytest.mark.parametrize("fixture", ["component5", "component6"])
  410. def test_unsupported_child_components(fixture, request):
  411. """Test that a value error is raised when an unsupported component (a child component found in the
  412. component's invalid children list) is provided as a child.
  413. Args:
  414. fixture: the test component as a fixture.
  415. request: Pytest request.
  416. """
  417. component = request.getfixturevalue(fixture)
  418. with pytest.raises(ValueError) as err:
  419. comp = component.create(rx.text("testing component"))
  420. comp.render()
  421. assert (
  422. err.value.args[0]
  423. == f"The component `{component.__name__}` cannot have `Text` as a child component"
  424. )
  425. @pytest.mark.parametrize("fixture", ["component5", "component7"])
  426. def test_component_with_only_valid_children(fixture, request):
  427. """Test that a value error is raised when an unsupported component (a child component not found in the
  428. component's valid children list) is provided as a child.
  429. Args:
  430. fixture: the test component as a fixture.
  431. request: Pytest request.
  432. """
  433. component = request.getfixturevalue(fixture)
  434. with pytest.raises(ValueError) as err:
  435. comp = component.create(rx.box("testing component"))
  436. comp.render()
  437. assert (
  438. err.value.args[0]
  439. == f"The component `{component.__name__}` only allows the components: `Text` as children. "
  440. f"Got `Box` instead."
  441. )
  442. @pytest.mark.parametrize(
  443. "component,rendered",
  444. [
  445. (rx.text("hi"), "<Text>\n {`hi`}\n</Text>"),
  446. (
  447. rx.box(rx.heading("test", size="md")),
  448. "<Box>\n <Heading size={`md`}>\n {`test`}\n</Heading>\n</Box>",
  449. ),
  450. ],
  451. )
  452. def test_format_component(component, rendered):
  453. """Test that a component is formatted correctly.
  454. Args:
  455. component: The component to format.
  456. rendered: The expected rendered component.
  457. """
  458. assert str(component) == rendered