test_component.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  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 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. @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": {ImportVar(tag="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": {ImportVar(tag="Component")}}
  149. assert c2.get_imports() == {
  150. "react-redux": {ImportVar(tag="connect")},
  151. "react": {ImportVar(tag="Component")},
  152. }
  153. def test_get_custom_code(component1, component2):
  154. """Test getting the custom code of a component.
  155. Args:
  156. component1: A test component.
  157. component2: A test component.
  158. """
  159. # Check that the code gets compiled correctly.
  160. c1 = component1.create()
  161. c2 = component2.create()
  162. assert c1.get_custom_code() == {"console.log('component1')"}
  163. assert c2.get_custom_code() == {"console.log('component2')"}
  164. # Check that nesting components compiles both codes.
  165. c1 = component1.create(c2)
  166. assert c1.get_custom_code() == {
  167. "console.log('component1')",
  168. "console.log('component2')",
  169. }
  170. # Check that code is not duplicated.
  171. c1 = component1.create(c2, c2, c1, c1)
  172. assert c1.get_custom_code() == {
  173. "console.log('component1')",
  174. "console.log('component2')",
  175. }
  176. def test_get_props(component1, component2):
  177. """Test that the props are set correctly.
  178. Args:
  179. component1: A test component.
  180. component2: A test component.
  181. """
  182. assert component1.get_props() == {"text", "number"}
  183. assert component2.get_props() == {"arr"}
  184. @pytest.mark.parametrize(
  185. "text,number",
  186. [
  187. ("", 0),
  188. ("test", 1),
  189. ("hi", -13),
  190. ],
  191. )
  192. def test_valid_props(component1, text: str, number: int):
  193. """Test that we can construct a component with valid props.
  194. Args:
  195. component1: A test component.
  196. text: A test string.
  197. number: A test number.
  198. """
  199. c = component1.create(text=text, number=number)
  200. assert c.text == text
  201. assert c.number == number
  202. @pytest.mark.parametrize(
  203. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  204. )
  205. def test_invalid_prop_type(component1, text: str, number: int):
  206. """Test that an invalid prop type raises an error.
  207. Args:
  208. component1: A test component.
  209. text: A test string.
  210. number: A test number.
  211. """
  212. # Check that
  213. with pytest.raises(TypeError):
  214. component1.create(text=text, number=number)
  215. def test_var_props(component1, test_state):
  216. """Test that we can set a Var prop.
  217. Args:
  218. component1: A test component.
  219. test_state: A test state.
  220. """
  221. c1 = component1.create(text="hello", number=test_state.num)
  222. assert c1.number == test_state.num
  223. def test_get_controlled_triggers(component1, component2):
  224. """Test that we can get the controlled triggers of a component.
  225. Args:
  226. component1: A test component.
  227. component2: A test component.
  228. """
  229. assert component1.get_controlled_triggers() == dict()
  230. assert set(component2.get_controlled_triggers()) == {"on_open", "on_close"}
  231. def test_get_triggers(component1, component2):
  232. """Test that we can get the triggers of a component.
  233. Args:
  234. component1: A test component.
  235. component2: A test component.
  236. """
  237. assert component1.get_triggers() == EVENT_TRIGGERS
  238. assert component2.get_triggers() == {"on_open", "on_close"} | EVENT_TRIGGERS
  239. def test_create_custom_component(my_component):
  240. """Test that we can create a custom component.
  241. Args:
  242. my_component: A test custom component.
  243. """
  244. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  245. assert component.tag == "MyComponent"
  246. assert component.get_props() == set()
  247. assert component.get_custom_components() == {component}
  248. def test_custom_component_hash(my_component):
  249. """Test that the hash of a custom component is correct.
  250. Args:
  251. my_component: A test custom component.
  252. """
  253. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  254. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  255. assert {component1, component2} == {component1}
  256. def test_custom_component_wrapper():
  257. """Test that the wrapper of a custom component is correct."""
  258. @custom_component
  259. def my_component(width: Var[int], color: Var[str]):
  260. return pc.box(
  261. width=width,
  262. color=color,
  263. )
  264. ccomponent = my_component(
  265. pc.text("child"), width=Var.create(1), color=Var.create("red")
  266. )
  267. assert isinstance(ccomponent, CustomComponent)
  268. assert len(ccomponent.children) == 1
  269. assert isinstance(ccomponent.children[0], pc.Text)
  270. component = ccomponent.get_component()
  271. assert isinstance(component, Box)
  272. def test_invalid_event_handler_args(component2, test_state):
  273. """Test that an invalid event handler raises an error.
  274. Args:
  275. component2: A test component.
  276. test_state: A test state.
  277. """
  278. # Uncontrolled event handlers should not take args.
  279. # This is okay.
  280. component2.create(on_click=test_state.do_something)
  281. # This is not okay.
  282. with pytest.raises(ValueError):
  283. component2.create(on_click=test_state.do_something_arg)
  284. # However lambdas are okay.
  285. component2.create(on_click=lambda: test_state.do_something_arg(1))
  286. component2.create(
  287. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something]
  288. )
  289. component2.create(
  290. on_click=lambda: [test_state.do_something_arg(1), test_state.do_something()]
  291. )
  292. # Controlled event handlers should take args.
  293. # This is okay.
  294. component2.create(on_open=test_state.do_something_arg)
  295. # do_something is allowed and will simply run while ignoring the arg
  296. component2.create(on_open=test_state.do_something)
  297. component2.create(on_open=[test_state.do_something_arg, test_state.do_something])
  298. def test_get_hooks_nested(component1, component2, component3):
  299. """Test that a component returns hooks from child components.
  300. Args:
  301. component1: test component.
  302. component2: another component.
  303. component3: component with hooks defined.
  304. """
  305. c = component1.create(
  306. component2.create(arr=[]),
  307. component3.create(),
  308. component3.create(),
  309. component3.create(),
  310. text="a",
  311. number=1,
  312. )
  313. assert c.get_hooks() == component3().get_hooks()
  314. def test_get_hooks_nested2(component3, component4):
  315. """Test that a component returns both when parent and child have hooks.
  316. Args:
  317. component3: component with hooks defined.
  318. component4: component with different hooks defined.
  319. """
  320. exp_hooks = component3().get_hooks().union(component4().get_hooks())
  321. assert component3.create(component4.create()).get_hooks() == exp_hooks
  322. assert component4.create(component3.create()).get_hooks() == exp_hooks
  323. assert (
  324. component4.create(
  325. component3.create(),
  326. component4.create(),
  327. component3.create(),
  328. ).get_hooks()
  329. == exp_hooks
  330. )