test_component.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  1. from typing import Dict, List, Type
  2. import pytest
  3. import pynecone as pc
  4. from pynecone.components.component import Component, CustomComponent, custom_component
  5. from pynecone.components.layout.box import Box
  6. from pynecone.event import EVENT_ARG, EVENT_TRIGGERS, EventHandler
  7. from pynecone.state import State
  8. from pynecone.style import Style
  9. from pynecone.utils import imports
  10. from pynecone.vars import ImportVar, Var
  11. @pytest.fixture
  12. def test_state():
  13. class TestState(State):
  14. num: int
  15. def do_something(self):
  16. pass
  17. def do_something_arg(self, arg):
  18. pass
  19. return TestState
  20. @pytest.fixture
  21. def component1() -> Type[Component]:
  22. """A test component.
  23. Returns:
  24. A test component.
  25. """
  26. class TestComponent1(Component):
  27. # A test string prop.
  28. text: Var[str]
  29. # A test number prop.
  30. number: Var[int]
  31. def _get_imports(self) -> imports.ImportDict:
  32. return {"react": {ImportVar(tag="Component")}}
  33. def _get_custom_code(self) -> str:
  34. return "console.log('component1')"
  35. return TestComponent1
  36. @pytest.fixture
  37. def component2() -> Type[Component]:
  38. """A test component.
  39. Returns:
  40. A test component.
  41. """
  42. class TestComponent2(Component):
  43. # A test list prop.
  44. arr: Var[List[str]]
  45. def get_controlled_triggers(self) -> Dict[str, Var]:
  46. """Test controlled triggers.
  47. Returns:
  48. Test controlled triggers.
  49. """
  50. return {
  51. "on_open": EVENT_ARG,
  52. "on_close": EVENT_ARG,
  53. }
  54. def _get_imports(self) -> imports.ImportDict:
  55. return {"react-redux": {ImportVar(tag="connect")}}
  56. def _get_custom_code(self) -> str:
  57. return "console.log('component2')"
  58. return TestComponent2
  59. @pytest.fixture
  60. def component3() -> Type[Component]:
  61. """A test component with hook defined.
  62. Returns:
  63. A test component.
  64. """
  65. class TestComponent3(Component):
  66. def _get_hooks(self) -> str:
  67. return "const a = () => true"
  68. return TestComponent3
  69. @pytest.fixture
  70. def component4() -> Type[Component]:
  71. """A test component with hook defined.
  72. Returns:
  73. A test component.
  74. """
  75. class TestComponent4(Component):
  76. def _get_hooks(self) -> str:
  77. return "const b = () => false"
  78. return TestComponent4
  79. @pytest.fixture
  80. def component5() -> Type[Component]:
  81. """A test component.
  82. Returns:
  83. A test component.
  84. """
  85. class TestComponent5(Component):
  86. tag = "Tag"
  87. invalid_children: List[str] = ["Text"]
  88. return TestComponent5
  89. @pytest.fixture
  90. def on_click1() -> EventHandler:
  91. """A sample on click function.
  92. Returns:
  93. A sample on click function.
  94. """
  95. def on_click1():
  96. pass
  97. return EventHandler(fn=on_click1)
  98. @pytest.fixture
  99. def on_click2() -> EventHandler:
  100. """A sample on click function.
  101. Returns:
  102. A sample on click function.
  103. """
  104. def on_click2():
  105. pass
  106. return EventHandler(fn=on_click2)
  107. @pytest.fixture
  108. def my_component():
  109. """A test component function.
  110. Returns:
  111. A test component function.
  112. """
  113. def my_component(prop1: Var[str], prop2: Var[int]):
  114. return Box.create(prop1, prop2)
  115. return my_component
  116. def test_set_style_attrs(component1):
  117. """Test that style attributes are set in the dict.
  118. Args:
  119. component1: A test component.
  120. """
  121. component = component1(color="white", text_align="center")
  122. assert component.style["color"] == "white"
  123. assert component.style["textAlign"] == "center"
  124. def test_create_component(component1):
  125. """Test that the component is created correctly.
  126. Args:
  127. component1: A test component.
  128. """
  129. children = [component1() for _ in range(3)]
  130. attrs = {"color": "white", "text_align": "center"}
  131. c = component1.create(*children, **attrs)
  132. assert isinstance(c, component1)
  133. assert c.children == children
  134. assert c.style == {"color": "white", "textAlign": "center"}
  135. def test_add_style(component1, component2):
  136. """Test adding a style to a component.
  137. Args:
  138. component1: A test component.
  139. component2: A test component.
  140. """
  141. style = {
  142. component1: Style({"color": "white"}),
  143. component2: Style({"color": "black"}),
  144. }
  145. c1 = component1().add_style(style) # type: ignore
  146. c2 = component2().add_style(style) # type: ignore
  147. assert c1.style["color"] == "white"
  148. assert c2.style["color"] == "black"
  149. def test_get_imports(component1, component2):
  150. """Test getting the imports of a component.
  151. Args:
  152. component1: A test component.
  153. component2: A test component.
  154. """
  155. c1 = component1.create()
  156. c2 = component2.create(c1)
  157. assert c1.get_imports() == {"react": {ImportVar(tag="Component")}}
  158. assert c2.get_imports() == {
  159. "react-redux": {ImportVar(tag="connect")},
  160. "react": {ImportVar(tag="Component")},
  161. }
  162. def test_get_custom_code(component1, component2):
  163. """Test getting the custom code of a component.
  164. Args:
  165. component1: A test component.
  166. component2: A test component.
  167. """
  168. # Check that the code gets compiled correctly.
  169. c1 = component1.create()
  170. c2 = component2.create()
  171. assert c1.get_custom_code() == {"console.log('component1')"}
  172. assert c2.get_custom_code() == {"console.log('component2')"}
  173. # Check that nesting components compiles both codes.
  174. c1 = component1.create(c2)
  175. assert c1.get_custom_code() == {
  176. "console.log('component1')",
  177. "console.log('component2')",
  178. }
  179. # Check that code is not duplicated.
  180. c1 = component1.create(c2, c2, c1, c1)
  181. assert c1.get_custom_code() == {
  182. "console.log('component1')",
  183. "console.log('component2')",
  184. }
  185. def test_get_props(component1, component2):
  186. """Test that the props are set correctly.
  187. Args:
  188. component1: A test component.
  189. component2: A test component.
  190. """
  191. assert component1.get_props() == {"text", "number"}
  192. assert component2.get_props() == {"arr"}
  193. @pytest.mark.parametrize(
  194. "text,number",
  195. [
  196. ("", 0),
  197. ("test", 1),
  198. ("hi", -13),
  199. ],
  200. )
  201. def test_valid_props(component1, text: str, number: int):
  202. """Test that we can construct a component with valid props.
  203. Args:
  204. component1: A test component.
  205. text: A test string.
  206. number: A test number.
  207. """
  208. c = component1.create(text=text, number=number)
  209. assert c.text == text
  210. assert c.number == number
  211. @pytest.mark.parametrize(
  212. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  213. )
  214. def test_invalid_prop_type(component1, text: str, number: int):
  215. """Test that an invalid prop type raises an error.
  216. Args:
  217. component1: A test component.
  218. text: A test string.
  219. number: A test number.
  220. """
  221. # Check that
  222. with pytest.raises(TypeError):
  223. component1.create(text=text, number=number)
  224. def test_var_props(component1, test_state):
  225. """Test that we can set a Var prop.
  226. Args:
  227. component1: A test component.
  228. test_state: A test state.
  229. """
  230. c1 = component1.create(text="hello", number=test_state.num)
  231. assert c1.number == test_state.num
  232. def test_get_controlled_triggers(component1, component2):
  233. """Test that we can get the controlled triggers of a component.
  234. Args:
  235. component1: A test component.
  236. component2: A test component.
  237. """
  238. assert component1().get_controlled_triggers() == dict()
  239. assert set(component2().get_controlled_triggers()) == {"on_open", "on_close"}
  240. def test_get_triggers(component1, component2):
  241. """Test that we can get the triggers of a component.
  242. Args:
  243. component1: A test component.
  244. component2: A test component.
  245. """
  246. assert component1().get_triggers() == EVENT_TRIGGERS
  247. assert component2().get_triggers() == {"on_open", "on_close"} | EVENT_TRIGGERS
  248. def test_create_custom_component(my_component):
  249. """Test that we can create a custom component.
  250. Args:
  251. my_component: A test custom component.
  252. """
  253. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  254. assert component.tag == "MyComponent"
  255. assert component.get_props() == set()
  256. assert component.get_custom_components() == {component}
  257. def test_custom_component_hash(my_component):
  258. """Test that the hash of a custom component is correct.
  259. Args:
  260. my_component: A test custom component.
  261. """
  262. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  263. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  264. assert {component1, component2} == {component1}
  265. def test_custom_component_wrapper():
  266. """Test that the wrapper of a custom component is correct."""
  267. @custom_component
  268. def my_component(width: Var[int], color: Var[str]):
  269. return pc.box(
  270. width=width,
  271. color=color,
  272. )
  273. ccomponent = my_component(
  274. pc.text("child"), width=Var.create(1), color=Var.create("red")
  275. )
  276. assert isinstance(ccomponent, CustomComponent)
  277. assert len(ccomponent.children) == 1
  278. assert isinstance(ccomponent.children[0], pc.Text)
  279. component = ccomponent.get_component()
  280. assert isinstance(component, Box)
  281. def test_invalid_event_handler_args(component2, test_state):
  282. """Test that an invalid event handler raises an error.
  283. Args:
  284. component2: A test component.
  285. test_state: A test state.
  286. """
  287. # Uncontrolled event handlers should not take args.
  288. # This is okay.
  289. component2.create(on_click=test_state.do_something)
  290. # This is not okay.
  291. with pytest.raises(ValueError):
  292. component2.create(on_click=test_state.do_something_arg)
  293. # However lambdas are okay.
  294. component2.create(on_click=lambda: test_state.do_something_arg(1))
  295. component2.create(
  296. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  297. )
  298. component2.create(
  299. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  300. )
  301. # Controlled event handlers should take args.
  302. # This is okay.
  303. component2.create(on_open=test_state.do_something_arg)
  304. # do_something is allowed and will simply run while ignoring the arg
  305. component2.create(on_open=test_state.do_something)
  306. component2.create(on_open=[test_state.do_something_arg, test_state.do_something])
  307. def test_get_hooks_nested(component1, component2, component3):
  308. """Test that a component returns hooks from child components.
  309. Args:
  310. component1: test component.
  311. component2: another component.
  312. component3: component with hooks defined.
  313. """
  314. c = component1.create(
  315. component2.create(arr=[]),
  316. component3.create(),
  317. component3.create(),
  318. component3.create(),
  319. text="a",
  320. number=1,
  321. )
  322. assert c.get_hooks() == component3().get_hooks()
  323. def test_get_hooks_nested2(component3, component4):
  324. """Test that a component returns both when parent and child have hooks.
  325. Args:
  326. component3: component with hooks defined.
  327. component4: component with different hooks defined.
  328. """
  329. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  330. assert component3.create(component4.create()).get_hooks() == exp_hooks
  331. assert component4.create(component3.create()).get_hooks() == exp_hooks
  332. assert (
  333. component4.create(
  334. component3.create(),
  335. component4.create(),
  336. component3.create(),
  337. ).get_hooks()
  338. == exp_hooks
  339. )
  340. def test_unsupported_child_components(component5):
  341. """Test that a value error is raised when an unsupported component is provided as a child.
  342. Args:
  343. component5: the test component
  344. """
  345. with pytest.raises(ValueError) as err:
  346. comp = component5.create(pc.text("testing component"))
  347. comp.render()
  348. assert (
  349. err.value.args[0]
  350. == f"The component `tag` cannot have `text` as a child component"
  351. )