test_component.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  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 on_click1() -> EventHandler:
  81. """A sample on click function.
  82. Returns:
  83. A sample on click function.
  84. """
  85. def on_click1():
  86. pass
  87. return EventHandler(fn=on_click1)
  88. @pytest.fixture
  89. def on_click2() -> EventHandler:
  90. """A sample on click function.
  91. Returns:
  92. A sample on click function.
  93. """
  94. def on_click2():
  95. pass
  96. return EventHandler(fn=on_click2)
  97. @pytest.fixture
  98. def my_component():
  99. """A test component function.
  100. Returns:
  101. A test component function.
  102. """
  103. def my_component(prop1: Var[str], prop2: Var[int]):
  104. return Box.create(prop1, prop2)
  105. return my_component
  106. def test_set_style_attrs(component1):
  107. """Test that style attributes are set in the dict.
  108. Args:
  109. component1: A test component.
  110. """
  111. component = component1(color="white", text_align="center")
  112. assert component.style["color"] == "white"
  113. assert component.style["textAlign"] == "center"
  114. def test_create_component(component1):
  115. """Test that the component is created correctly.
  116. Args:
  117. component1: A test component.
  118. """
  119. children = [component1() for _ in range(3)]
  120. attrs = {"color": "white", "text_align": "center"}
  121. c = component1.create(*children, **attrs)
  122. assert isinstance(c, component1)
  123. assert c.children == children
  124. assert c.style == {"color": "white", "textAlign": "center"}
  125. def test_add_style(component1, component2):
  126. """Test adding a style to a component.
  127. Args:
  128. component1: A test component.
  129. component2: A test component.
  130. """
  131. style = {
  132. component1: Style({"color": "white"}),
  133. component2: Style({"color": "black"}),
  134. }
  135. c1 = component1().add_style(style) # type: ignore
  136. c2 = component2().add_style(style) # type: ignore
  137. assert c1.style["color"] == "white"
  138. assert c2.style["color"] == "black"
  139. def test_get_imports(component1, component2):
  140. """Test getting the imports of a component.
  141. Args:
  142. component1: A test component.
  143. component2: A test component.
  144. """
  145. c1 = component1.create()
  146. c2 = component2.create(c1)
  147. assert c1.get_imports() == {"react": {ImportVar(tag="Component")}}
  148. assert c2.get_imports() == {
  149. "react-redux": {ImportVar(tag="connect")},
  150. "react": {ImportVar(tag="Component")},
  151. }
  152. def test_get_custom_code(component1, component2):
  153. """Test getting the custom code of a component.
  154. Args:
  155. component1: A test component.
  156. component2: A test component.
  157. """
  158. # Check that the code gets compiled correctly.
  159. c1 = component1.create()
  160. c2 = component2.create()
  161. assert c1.get_custom_code() == {"console.log('component1')"}
  162. assert c2.get_custom_code() == {"console.log('component2')"}
  163. # Check that nesting components compiles both codes.
  164. c1 = component1.create(c2)
  165. assert c1.get_custom_code() == {
  166. "console.log('component1')",
  167. "console.log('component2')",
  168. }
  169. # Check that code is not duplicated.
  170. c1 = component1.create(c2, c2, c1, c1)
  171. assert c1.get_custom_code() == {
  172. "console.log('component1')",
  173. "console.log('component2')",
  174. }
  175. def test_get_props(component1, component2):
  176. """Test that the props are set correctly.
  177. Args:
  178. component1: A test component.
  179. component2: A test component.
  180. """
  181. assert component1.get_props() == {"text", "number"}
  182. assert component2.get_props() == {"arr"}
  183. @pytest.mark.parametrize(
  184. "text,number",
  185. [
  186. ("", 0),
  187. ("test", 1),
  188. ("hi", -13),
  189. ],
  190. )
  191. def test_valid_props(component1, text: str, number: int):
  192. """Test that we can construct a component with valid props.
  193. Args:
  194. component1: A test component.
  195. text: A test string.
  196. number: A test number.
  197. """
  198. c = component1.create(text=text, number=number)
  199. assert c.text == text
  200. assert c.number == number
  201. @pytest.mark.parametrize(
  202. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  203. )
  204. def test_invalid_prop_type(component1, text: str, number: int):
  205. """Test that an invalid prop type raises an error.
  206. Args:
  207. component1: A test component.
  208. text: A test string.
  209. number: A test number.
  210. """
  211. # Check that
  212. with pytest.raises(TypeError):
  213. component1.create(text=text, number=number)
  214. def test_var_props(component1, test_state):
  215. """Test that we can set a Var prop.
  216. Args:
  217. component1: A test component.
  218. test_state: A test state.
  219. """
  220. c1 = component1.create(text="hello", number=test_state.num)
  221. assert c1.number == test_state.num
  222. def test_get_controlled_triggers(component1, component2):
  223. """Test that we can get the controlled triggers of a component.
  224. Args:
  225. component1: A test component.
  226. component2: A test component.
  227. """
  228. assert component1().get_controlled_triggers() == dict()
  229. assert set(component2().get_controlled_triggers()) == {"on_open", "on_close"}
  230. def test_get_triggers(component1, component2):
  231. """Test that we can get the triggers of a component.
  232. Args:
  233. component1: A test component.
  234. component2: A test component.
  235. """
  236. assert component1().get_triggers() == EVENT_TRIGGERS
  237. assert component2().get_triggers() == {"on_open", "on_close"} | EVENT_TRIGGERS
  238. def test_create_custom_component(my_component):
  239. """Test that we can create a custom component.
  240. Args:
  241. my_component: A test custom component.
  242. """
  243. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  244. assert component.tag == "MyComponent"
  245. assert component.get_props() == set()
  246. assert component.get_custom_components() == {component}
  247. def test_custom_component_hash(my_component):
  248. """Test that the hash of a custom component is correct.
  249. Args:
  250. my_component: A test custom component.
  251. """
  252. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  253. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  254. assert {component1, component2} == {component1}
  255. def test_custom_component_wrapper():
  256. """Test that the wrapper of a custom component is correct."""
  257. @custom_component
  258. def my_component(width: Var[int], color: Var[str]):
  259. return pc.box(
  260. width=width,
  261. color=color,
  262. )
  263. ccomponent = my_component(
  264. pc.text("child"), width=Var.create(1), color=Var.create("red")
  265. )
  266. assert isinstance(ccomponent, CustomComponent)
  267. assert len(ccomponent.children) == 1
  268. assert isinstance(ccomponent.children[0], pc.Text)
  269. component = ccomponent.get_component()
  270. assert isinstance(component, Box)
  271. def test_invalid_event_handler_args(component2, test_state):
  272. """Test that an invalid event handler raises an error.
  273. Args:
  274. component2: A test component.
  275. test_state: A test state.
  276. """
  277. # Uncontrolled event handlers should not take args.
  278. # This is okay.
  279. component2.create(on_click=test_state.do_something)
  280. # This is not okay.
  281. with pytest.raises(ValueError):
  282. component2.create(on_click=test_state.do_something_arg)
  283. # However lambdas are okay.
  284. component2.create(on_click=lambda: test_state.do_something_arg(1))
  285. component2.create(
  286. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  287. )
  288. component2.create(
  289. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  290. )
  291. # Controlled event handlers should take args.
  292. # This is okay.
  293. component2.create(on_open=test_state.do_something_arg)
  294. # do_something is allowed and will simply run while ignoring the arg
  295. component2.create(on_open=test_state.do_something)
  296. component2.create(on_open=[test_state.do_something_arg, test_state.do_something])
  297. def test_get_hooks_nested(component1, component2, component3):
  298. """Test that a component returns hooks from child components.
  299. Args:
  300. component1: test component.
  301. component2: another component.
  302. component3: component with hooks defined.
  303. """
  304. c = component1.create(
  305. component2.create(arr=[]),
  306. component3.create(),
  307. component3.create(),
  308. component3.create(),
  309. text="a",
  310. number=1,
  311. )
  312. assert c.get_hooks() == component3().get_hooks()
  313. def test_get_hooks_nested2(component3, component4):
  314. """Test that a component returns both when parent and child have hooks.
  315. Args:
  316. component3: component with hooks defined.
  317. component4: component with different hooks defined.
  318. """
  319. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  320. assert component3.create(component4.create()).get_hooks() == exp_hooks
  321. assert component4.create(component3.create()).get_hooks() == exp_hooks
  322. assert (
  323. component4.create(
  324. component3.create(),
  325. component4.create(),
  326. component3.create(),
  327. ).get_hooks()
  328. == exp_hooks
  329. )