test_component.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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.var import Var
  11. @pytest.fixture
  12. def TestState():
  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": {"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. @classmethod
  46. def get_controlled_triggers(cls) -> Dict[str, Var]:
  47. """Test controlled triggers.
  48. Returns:
  49. Test controlled triggers.
  50. """
  51. return {
  52. "on_open": EVENT_ARG,
  53. "on_close": EVENT_ARG,
  54. }
  55. def _get_imports(self) -> imports.ImportDict:
  56. return {"react-redux": {"connect"}}
  57. def _get_custom_code(self) -> str:
  58. return "console.log('component2')"
  59. return TestComponent2
  60. @pytest.fixture
  61. def component3() -> Type[Component]:
  62. """A test component with hook defined.
  63. Returns:
  64. A test component.
  65. """
  66. class TestComponent3(Component):
  67. def _get_hooks(self) -> str:
  68. return "const a = () => true"
  69. return TestComponent3
  70. @pytest.fixture
  71. def component4() -> Type[Component]:
  72. """A test component with hook defined.
  73. Returns:
  74. A test component.
  75. """
  76. class TestComponent4(Component):
  77. def _get_hooks(self) -> str:
  78. return "const b = () => false"
  79. return TestComponent4
  80. @pytest.fixture
  81. def on_click1() -> EventHandler:
  82. """A sample on click function.
  83. Returns:
  84. A sample on click function.
  85. """
  86. def on_click1():
  87. pass
  88. return EventHandler(fn=on_click1)
  89. @pytest.fixture
  90. def on_click2() -> EventHandler:
  91. """A sample on click function.
  92. Returns:
  93. A sample on click function.
  94. """
  95. def on_click2():
  96. pass
  97. return EventHandler(fn=on_click2)
  98. @pytest.fixture
  99. def my_component():
  100. """A test component function.
  101. Returns:
  102. A test component function.
  103. """
  104. def my_component(prop1: Var[str], prop2: Var[int]):
  105. return Box.create(prop1, prop2)
  106. return my_component
  107. def test_set_style_attrs(component1):
  108. """Test that style attributes are set in the dict.
  109. Args:
  110. component1: A test component.
  111. """
  112. component = component1(color="white", text_align="center")
  113. assert component.style["color"] == "white"
  114. assert component.style["textAlign"] == "center"
  115. def test_create_component(component1):
  116. """Test that the component is created correctly.
  117. Args:
  118. component1: A test component.
  119. """
  120. children = [component1() for _ in range(3)]
  121. attrs = {"color": "white", "text_align": "center"}
  122. c = component1.create(*children, **attrs)
  123. assert isinstance(c, component1)
  124. assert c.children == children
  125. assert c.style == {"color": "white", "textAlign": "center"}
  126. def test_add_style(component1, component2):
  127. """Test adding a style to a component.
  128. Args:
  129. component1: A test component.
  130. component2: A test component.
  131. """
  132. style = {
  133. component1: Style({"color": "white"}),
  134. component2: Style({"color": "black"}),
  135. }
  136. c1 = component1().add_style(style) # type: ignore
  137. c2 = component2().add_style(style) # type: ignore
  138. assert c1.style["color"] == "white"
  139. assert c2.style["color"] == "black"
  140. def test_get_imports(component1, component2):
  141. """Test getting the imports of a component.
  142. Args:
  143. component1: A test component.
  144. component2: A test component.
  145. """
  146. c1 = component1.create()
  147. c2 = component2.create(c1)
  148. assert c1.get_imports() == {"react": {"Component"}}
  149. assert c2.get_imports() == {"react-redux": {"connect"}, "react": {"Component"}}
  150. def test_get_custom_code(component1, component2):
  151. """Test getting the custom code of a component.
  152. Args:
  153. component1: A test component.
  154. component2: A test component.
  155. """
  156. # Check that the code gets compiled correctly.
  157. c1 = component1.create()
  158. c2 = component2.create()
  159. assert c1.get_custom_code() == {"console.log('component1')"}
  160. assert c2.get_custom_code() == {"console.log('component2')"}
  161. # Check that nesting components compiles both codes.
  162. c1 = component1.create(c2)
  163. assert c1.get_custom_code() == {
  164. "console.log('component1')",
  165. "console.log('component2')",
  166. }
  167. # Check that code is not duplicated.
  168. c1 = component1.create(c2, c2, c1, c1)
  169. assert c1.get_custom_code() == {
  170. "console.log('component1')",
  171. "console.log('component2')",
  172. }
  173. def test_get_props(component1, component2):
  174. """Test that the props are set correctly.
  175. Args:
  176. component1: A test component.
  177. component2: A test component.
  178. """
  179. assert component1.get_props() == {"text", "number"}
  180. assert component2.get_props() == {"arr"}
  181. @pytest.mark.parametrize(
  182. "text,number",
  183. [
  184. ("", 0),
  185. ("test", 1),
  186. ("hi", -13),
  187. ],
  188. )
  189. def test_valid_props(component1, text: str, number: int):
  190. """Test that we can construct a component with valid props.
  191. Args:
  192. component1: A test component.
  193. text: A test string.
  194. number: A test number.
  195. """
  196. c = component1.create(text=text, number=number)
  197. assert c.text == text
  198. assert c.number == number
  199. @pytest.mark.parametrize(
  200. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  201. )
  202. def test_invalid_prop_type(component1, text: str, number: int):
  203. """Test that an invalid prop type raises an error.
  204. Args:
  205. component1: A test component.
  206. text: A test string.
  207. number: A test number.
  208. """
  209. # Check that
  210. with pytest.raises(TypeError):
  211. component1.create(text=text, number=number)
  212. def test_var_props(component1, TestState):
  213. """Test that we can set a Var prop.
  214. Args:
  215. component1: A test component.
  216. TestState: A test state.
  217. """
  218. c1 = component1.create(text="hello", number=TestState.num)
  219. assert c1.number == TestState.num
  220. def test_get_controlled_triggers(component1, component2):
  221. """Test that we can get the controlled triggers of a component.
  222. Args:
  223. component1: A test component.
  224. component2: A test component.
  225. """
  226. assert component1.get_controlled_triggers() == dict()
  227. assert set(component2.get_controlled_triggers()) == {"on_open", "on_close"}
  228. def test_get_triggers(component1, component2):
  229. """Test that we can get the triggers of a component.
  230. Args:
  231. component1: A test component.
  232. component2: A test component.
  233. """
  234. assert component1.get_triggers() == EVENT_TRIGGERS
  235. assert component2.get_triggers() == {"on_open", "on_close"} | EVENT_TRIGGERS
  236. def test_create_custom_component(my_component):
  237. """Test that we can create a custom component.
  238. Args:
  239. my_component: A test custom component.
  240. """
  241. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  242. assert component.tag == "MyComponent"
  243. assert component.get_props() == set()
  244. assert component.get_custom_components() == {component}
  245. def test_custom_component_hash(my_component):
  246. """Test that the hash of a custom component is correct.
  247. Args:
  248. my_component: A test custom component.
  249. """
  250. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  251. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  252. assert {component1, component2} == {component1}
  253. def test_custom_component_wrapper():
  254. """Test that the wrapper of a custom component is correct."""
  255. @custom_component
  256. def my_component(width: Var[int], color: Var[str]):
  257. return pc.box(
  258. width=width,
  259. color=color,
  260. )
  261. ccomponent = my_component(
  262. pc.text("child"), width=Var.create(1), color=Var.create("red")
  263. )
  264. assert isinstance(ccomponent, CustomComponent)
  265. assert len(ccomponent.children) == 1
  266. assert isinstance(ccomponent.children[0], pc.Text)
  267. component = ccomponent.get_component()
  268. assert isinstance(component, Box)
  269. def test_invalid_event_handler_args(component2, TestState):
  270. """Test that an invalid event handler raises an error.
  271. Args:
  272. component2: A test component.
  273. TestState: A test state.
  274. """
  275. # Uncontrolled event handlers should not take args.
  276. # This is okay.
  277. component2.create(on_click=TestState.do_something)
  278. # This is not okay.
  279. with pytest.raises(ValueError):
  280. component2.create(on_click=TestState.do_something_arg)
  281. # However lambdas are okay.
  282. component2.create(on_click=lambda: TestState.do_something_arg(1))
  283. component2.create(
  284. on_click=lambda: [TestState.do_something_arg(1), TestState.do_something]
  285. )
  286. component2.create(
  287. on_click=lambda: [TestState.do_something_arg(1), TestState.do_something()]
  288. )
  289. # Controlled event handlers should take args.
  290. # This is okay.
  291. component2.create(on_open=TestState.do_something_arg)
  292. # This is not okay.
  293. with pytest.raises(ValueError):
  294. component2.create(on_open=TestState.do_something)
  295. with pytest.raises(ValueError):
  296. component2.create(on_open=[TestState.do_something_arg, TestState.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. )