test_component.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. from typing import Dict, List, Type
  2. import pytest
  3. from pynecone.components.component import Component, CustomComponent, ImportDict
  4. from pynecone.components.layout.box import Box
  5. from pynecone.event import EVENT_ARG, EVENT_TRIGGERS, EventHandler
  6. from pynecone.state import State
  7. from pynecone.style import Style
  8. from pynecone.var import Var
  9. @pytest.fixture
  10. def TestState():
  11. class TestState(State):
  12. num: int
  13. def do_something(self):
  14. pass
  15. def do_something_arg(self, arg):
  16. pass
  17. return TestState
  18. @pytest.fixture
  19. def component1() -> Type[Component]:
  20. """A test component.
  21. Returns:
  22. A test component.
  23. """
  24. class TestComponent1(Component):
  25. # A test string prop.
  26. text: Var[str]
  27. # A test number prop.
  28. number: Var[int]
  29. def _get_imports(self) -> ImportDict:
  30. return {"react": {"Component"}}
  31. def _get_custom_code(self) -> str:
  32. return "console.log('component1')"
  33. return TestComponent1
  34. @pytest.fixture
  35. def component2() -> Type[Component]:
  36. """A test component.
  37. Returns:
  38. A test component.
  39. """
  40. class TestComponent2(Component):
  41. # A test list prop.
  42. arr: Var[List[str]]
  43. @classmethod
  44. def get_controlled_triggers(cls) -> Dict[str, Var]:
  45. """Test controlled triggers.
  46. Returns:
  47. Test controlled triggers.
  48. """
  49. return {
  50. "on_open": EVENT_ARG,
  51. "on_close": EVENT_ARG,
  52. }
  53. def _get_imports(self) -> ImportDict:
  54. return {"react-redux": {"connect"}}
  55. def _get_custom_code(self) -> str:
  56. return "console.log('component2')"
  57. return TestComponent2
  58. @pytest.fixture
  59. def on_click1() -> EventHandler:
  60. """A sample on click function.
  61. Returns:
  62. A sample on click function.
  63. """
  64. def on_click1():
  65. pass
  66. return EventHandler(fn=on_click1)
  67. @pytest.fixture
  68. def on_click2() -> EventHandler:
  69. """A sample on click function.
  70. Returns:
  71. A sample on click function.
  72. """
  73. def on_click2():
  74. pass
  75. return EventHandler(fn=on_click2)
  76. @pytest.fixture
  77. def my_component():
  78. """A test component function.
  79. Returns:
  80. A test component function.
  81. """
  82. def my_component(prop1: Var[str], prop2: Var[int]):
  83. return Box.create(prop1, prop2)
  84. return my_component
  85. def test_set_style_attrs(component1):
  86. """Test that style attributes are set in the dict.
  87. Args:
  88. component1: A test component.
  89. """
  90. component = component1(color="white", text_align="center")
  91. assert component.style["color"] == "white"
  92. assert component.style["textAlign"] == "center"
  93. def test_create_component(component1):
  94. """Test that the component is created correctly.
  95. Args:
  96. component1: A test component.
  97. """
  98. children = [component1() for _ in range(3)]
  99. attrs = {"color": "white", "text_align": "center"}
  100. c = component1.create(*children, **attrs)
  101. assert isinstance(c, component1)
  102. assert c.children == children
  103. assert c.style == {"color": "white", "textAlign": "center"}
  104. def test_add_style(component1, component2):
  105. """Test adding a style to a component.
  106. Args:
  107. component1: A test component.
  108. component2: A test component.
  109. """
  110. style = {
  111. component1: Style({"color": "white"}),
  112. component2: Style({"color": "black"}),
  113. }
  114. c1 = component1().add_style(style) # type: ignore
  115. c2 = component2().add_style(style) # type: ignore
  116. assert c1.style["color"] == "white"
  117. assert c2.style["color"] == "black"
  118. def test_get_imports(component1, component2):
  119. """Test getting the imports of a component.
  120. Args:
  121. component1: A test component.
  122. component2: A test component.
  123. """
  124. c1 = component1.create()
  125. c2 = component2.create(c1)
  126. assert c1.get_imports() == {"react": {"Component"}}
  127. assert c2.get_imports() == {"react-redux": {"connect"}, "react": {"Component"}}
  128. def test_get_custom_code(component1, component2):
  129. """Test getting the custom code of a component.
  130. Args:
  131. component1: A test component.
  132. component2: A test component.
  133. """
  134. # Check that the code gets compiled correctly.
  135. c1 = component1.create()
  136. c2 = component2.create()
  137. assert c1.get_custom_code() == {"console.log('component1')"}
  138. assert c2.get_custom_code() == {"console.log('component2')"}
  139. # Check that nesting components compiles both codes.
  140. c1 = component1.create(c2)
  141. assert c1.get_custom_code() == {
  142. "console.log('component1')",
  143. "console.log('component2')",
  144. }
  145. # Check that code is not duplicated.
  146. c1 = component1.create(c2, c2, c1, c1)
  147. assert c1.get_custom_code() == {
  148. "console.log('component1')",
  149. "console.log('component2')",
  150. }
  151. def test_get_props(component1, component2):
  152. """Test that the props are set correctly.
  153. Args:
  154. component1: A test component.
  155. component2: A test component.
  156. """
  157. assert component1.get_props() == {"text", "number"}
  158. assert component2.get_props() == {"arr"}
  159. @pytest.mark.parametrize(
  160. "text,number",
  161. [
  162. ("", 0),
  163. ("test", 1),
  164. ("hi", -13),
  165. ],
  166. )
  167. def test_valid_props(component1, text: str, number: int):
  168. """Test that we can construct a component with valid props.
  169. Args:
  170. component1: A test component.
  171. text: A test string.
  172. number: A test number.
  173. """
  174. c = component1.create(text=text, number=number)
  175. assert c.text == text
  176. assert c.number == number
  177. @pytest.mark.parametrize(
  178. "text,number", [("", "bad_string"), (13, 1), (None, 1), ("test", [1, 2, 3])]
  179. )
  180. def test_invalid_prop_type(component1, text: str, number: int):
  181. """Test that an invalid prop type raises an error.
  182. Args:
  183. component1: A test component.
  184. text: A test string.
  185. number: A test number.
  186. """
  187. # Check that
  188. with pytest.raises(TypeError):
  189. component1.create(text=text, number=number)
  190. def test_var_props(component1, TestState):
  191. """Test that we can set a Var prop.
  192. Args:
  193. component1: A test component.
  194. TestState: A test state.
  195. """
  196. c1 = component1.create(text="hello", number=TestState.num)
  197. assert c1.number == TestState.num
  198. def test_get_controlled_triggers(component1, component2):
  199. """Test that we can get the controlled triggers of a component.
  200. Args:
  201. component1: A test component.
  202. component2: A test component.
  203. """
  204. assert component1.get_controlled_triggers() == dict()
  205. assert set(component2.get_controlled_triggers()) == {"on_open", "on_close"}
  206. def test_get_triggers(component1, component2):
  207. """Test that we can get the triggers of a component.
  208. Args:
  209. component1: A test component.
  210. component2: A test component.
  211. """
  212. assert component1.get_triggers() == EVENT_TRIGGERS
  213. assert component2.get_triggers() == {"on_open", "on_close"} | EVENT_TRIGGERS
  214. def test_create_custom_component(my_component):
  215. """Test that we can create a custom component.
  216. Args:
  217. my_component: A test custom component.
  218. """
  219. component = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  220. assert component.tag == "MyComponent"
  221. assert component.get_props() == set()
  222. assert component.get_custom_components() == {component}
  223. def test_custom_component_hash(my_component):
  224. """Test that the hash of a custom component is correct.
  225. Args:
  226. my_component: A test custom component.
  227. """
  228. component1 = CustomComponent(component_fn=my_component, prop1="test", prop2=1)
  229. component2 = CustomComponent(component_fn=my_component, prop1="test", prop2=2)
  230. assert {component1, component2} == {component1}
  231. def test_invalid_event_handler_args(component2, TestState):
  232. """Test that an invalid event handler raises an error.
  233. Args:
  234. component2: A test component.
  235. TestState: A test state.
  236. """
  237. # Uncontrolled event handlers should not take args.
  238. # This is okay.
  239. component2.create(on_click=TestState.do_something)
  240. # This is not okay.
  241. with pytest.raises(ValueError):
  242. component2.create(on_click=TestState.do_something_arg)
  243. # However lambdas are okay.
  244. component2.create(on_click=lambda: TestState.do_something_arg(1))
  245. component2.create(
  246. on_click=lambda: [TestState.do_something_arg(1), TestState.do_something]
  247. )
  248. component2.create(
  249. on_click=lambda: [TestState.do_something_arg(1), TestState.do_something()]
  250. )
  251. # Controlled event handlers should take args.
  252. # This is okay.
  253. component2.create(on_open=TestState.do_something_arg)
  254. # This is not okay.
  255. with pytest.raises(ValueError):
  256. component2.create(on_open=TestState.do_something)
  257. with pytest.raises(ValueError):
  258. component2.create(on_open=[TestState.do_something_arg, TestState.do_something])