test_event_actions.py 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. """Ensure stopPropagation and preventDefault work as expected."""
  2. import asyncio
  3. from typing import Callable, Coroutine, Generator
  4. import pytest
  5. from selenium.webdriver.common.by import By
  6. from reflex.testing import AppHarness, WebDriver
  7. def TestEventAction():
  8. """App for testing event_actions."""
  9. import reflex as rx
  10. class EventActionState(rx.State):
  11. order: list[str]
  12. def on_click(self, ev):
  13. self.order.append(f"on_click:{ev}")
  14. def on_click2(self):
  15. self.order.append("on_click2")
  16. class EventFiringComponent(rx.Component):
  17. """A component that fires onClick event without passing DOM event."""
  18. tag = "EventFiringComponent"
  19. def _get_custom_code(self) -> str | None:
  20. return """
  21. function EventFiringComponent(props) {
  22. return (
  23. <div id={props.id} onClick={(e) => props.onClick("foo")}>
  24. Event Firing Component
  25. </div>
  26. )
  27. }"""
  28. def get_event_triggers(self):
  29. return {"on_click": lambda: []}
  30. def index():
  31. return rx.vstack(
  32. rx.chakra.input(
  33. value=EventActionState.router.session.client_token,
  34. is_read_only=True,
  35. id="token",
  36. ),
  37. rx.button("No events", id="btn-no-events"),
  38. rx.button(
  39. "Stop Prop Only",
  40. id="btn-stop-prop-only",
  41. on_click=rx.stop_propagation, # type: ignore
  42. ),
  43. rx.button(
  44. "Click event",
  45. on_click=EventActionState.on_click("no_event_actions"), # type: ignore
  46. id="btn-click-event",
  47. ),
  48. rx.button(
  49. "Click stop propagation",
  50. on_click=EventActionState.on_click("stop_propagation").stop_propagation, # type: ignore
  51. id="btn-click-stop-propagation",
  52. ),
  53. rx.button(
  54. "Click stop propagation2",
  55. on_click=EventActionState.on_click2.stop_propagation,
  56. id="btn-click-stop-propagation2",
  57. ),
  58. rx.button(
  59. "Click event 2",
  60. on_click=EventActionState.on_click2,
  61. id="btn-click-event2",
  62. ),
  63. rx.link(
  64. "Link",
  65. href="#",
  66. on_click=EventActionState.on_click("link_no_event_actions"), # type: ignore
  67. id="link",
  68. ),
  69. rx.link(
  70. "Link Stop Propagation",
  71. href="#",
  72. on_click=EventActionState.on_click( # type: ignore
  73. "link_stop_propagation"
  74. ).stop_propagation,
  75. id="link-stop-propagation",
  76. ),
  77. rx.link(
  78. "Link Prevent Default Only",
  79. href="/invalid",
  80. on_click=rx.prevent_default, # type: ignore
  81. id="link-prevent-default-only",
  82. ),
  83. rx.link(
  84. "Link Prevent Default",
  85. href="/invalid",
  86. on_click=EventActionState.on_click( # type: ignore
  87. "link_prevent_default"
  88. ).prevent_default,
  89. id="link-prevent-default",
  90. ),
  91. rx.link(
  92. "Link Both",
  93. href="/invalid",
  94. on_click=EventActionState.on_click( # type: ignore
  95. "link_both"
  96. ).stop_propagation.prevent_default,
  97. id="link-stop-propagation-prevent-default",
  98. ),
  99. EventFiringComponent.create(
  100. id="custom-stop-propagation",
  101. on_click=EventActionState.on_click( # type: ignore
  102. "custom-stop-propagation"
  103. ).stop_propagation,
  104. ),
  105. EventFiringComponent.create(
  106. id="custom-prevent-default",
  107. on_click=EventActionState.on_click( # type: ignore
  108. "custom-prevent-default"
  109. ).prevent_default,
  110. ),
  111. rx.chakra.list(
  112. rx.foreach(
  113. EventActionState.order, # type: ignore
  114. rx.chakra.list_item,
  115. ),
  116. ),
  117. on_click=EventActionState.on_click("outer"), # type: ignore
  118. )
  119. app = rx.App(state=rx.State)
  120. app.add_page(index)
  121. @pytest.fixture(scope="session")
  122. def event_action(tmp_path_factory) -> Generator[AppHarness, None, None]:
  123. """Start TestEventAction app at tmp_path via AppHarness.
  124. Args:
  125. tmp_path_factory: pytest tmp_path_factory fixture
  126. Yields:
  127. running AppHarness instance
  128. """
  129. with AppHarness.create(
  130. root=tmp_path_factory.mktemp(f"event_action"),
  131. app_source=TestEventAction, # type: ignore
  132. ) as harness:
  133. yield harness
  134. @pytest.fixture
  135. def driver(event_action: AppHarness) -> Generator[WebDriver, None, None]:
  136. """Get an instance of the browser open to the event_action app.
  137. Args:
  138. event_action: harness for TestEventAction app
  139. Yields:
  140. WebDriver instance.
  141. """
  142. assert event_action.app_instance is not None, "app is not running"
  143. driver = event_action.frontend()
  144. try:
  145. yield driver
  146. finally:
  147. driver.quit()
  148. @pytest.fixture()
  149. def token(event_action: AppHarness, driver: WebDriver) -> str:
  150. """Get the token associated with backend state.
  151. Args:
  152. event_action: harness for TestEventAction app.
  153. driver: WebDriver instance.
  154. Returns:
  155. The token visible in the driver browser.
  156. """
  157. assert event_action.app_instance is not None
  158. token_input = driver.find_element(By.ID, "token")
  159. assert token_input
  160. # wait for the backend connection to send the token
  161. token = event_action.poll_for_value(token_input)
  162. assert token is not None
  163. return token
  164. @pytest.fixture()
  165. def poll_for_order(
  166. event_action: AppHarness, token: str
  167. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  168. """Poll for the order list to match the expected order.
  169. Args:
  170. event_action: harness for TestEventAction app.
  171. token: The token visible in the driver browser.
  172. Returns:
  173. An async function that polls for the order list to match the expected order.
  174. """
  175. async def _poll_for_order(exp_order: list[str]):
  176. async def _backend_state():
  177. return await event_action.get_state(f"{token}_state.event_action_state")
  178. async def _check():
  179. return (await _backend_state()).substates[
  180. "event_action_state"
  181. ].order == exp_order
  182. await AppHarness._poll_for_async(_check)
  183. assert (await _backend_state()).substates[
  184. "event_action_state"
  185. ].order == exp_order
  186. return _poll_for_order
  187. @pytest.mark.parametrize(
  188. ("element_id", "exp_order"),
  189. [
  190. ("btn-no-events", ["on_click:outer"]),
  191. ("btn-stop-prop-only", []),
  192. ("btn-click-event", ["on_click:no_event_actions", "on_click:outer"]),
  193. ("btn-click-stop-propagation", ["on_click:stop_propagation"]),
  194. ("btn-click-stop-propagation2", ["on_click2"]),
  195. ("btn-click-event2", ["on_click2", "on_click:outer"]),
  196. ("link", ["on_click:link_no_event_actions", "on_click:outer"]),
  197. ("link-stop-propagation", ["on_click:link_stop_propagation"]),
  198. ("link-prevent-default", ["on_click:link_prevent_default", "on_click:outer"]),
  199. ("link-prevent-default-only", ["on_click:outer"]),
  200. ("link-stop-propagation-prevent-default", ["on_click:link_both"]),
  201. (
  202. "custom-stop-propagation",
  203. ["on_click:custom-stop-propagation", "on_click:outer"],
  204. ),
  205. (
  206. "custom-prevent-default",
  207. ["on_click:custom-prevent-default", "on_click:outer"],
  208. ),
  209. ],
  210. )
  211. @pytest.mark.usefixtures("token")
  212. @pytest.mark.asyncio
  213. async def test_event_actions(
  214. driver: WebDriver,
  215. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  216. element_id: str,
  217. exp_order: list[str],
  218. ):
  219. """Click links and buttons and assert on fired events.
  220. Args:
  221. driver: WebDriver instance.
  222. poll_for_order: function that polls for the order list to match the expected order.
  223. element_id: The id of the element to click.
  224. exp_order: The expected order of events.
  225. """
  226. el = driver.find_element(By.ID, element_id)
  227. assert el
  228. prev_url = driver.current_url
  229. el.click()
  230. if "on_click:outer" not in exp_order:
  231. # really make sure the outer event is not fired
  232. await asyncio.sleep(0.5)
  233. await poll_for_order(exp_order)
  234. if element_id.startswith("link") and "prevent-default" not in element_id:
  235. assert driver.current_url != prev_url
  236. else:
  237. assert driver.current_url == prev_url