test_event_actions.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  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.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.list(
  112. rx.foreach(
  113. EventActionState.order, # type: ignore
  114. rx.list_item,
  115. ),
  116. ),
  117. on_click=EventActionState.on_click("outer"), # type: ignore
  118. )
  119. app = rx.App(state=EventActionState)
  120. app.add_page(index)
  121. app.compile()
  122. @pytest.fixture(scope="session")
  123. def event_action(tmp_path_factory) -> Generator[AppHarness, None, None]:
  124. """Start TestEventAction app at tmp_path via AppHarness.
  125. Args:
  126. tmp_path_factory: pytest tmp_path_factory fixture
  127. Yields:
  128. running AppHarness instance
  129. """
  130. with AppHarness.create(
  131. root=tmp_path_factory.mktemp(f"event_action"),
  132. app_source=TestEventAction, # type: ignore
  133. ) as harness:
  134. yield harness
  135. @pytest.fixture
  136. def driver(event_action: AppHarness) -> Generator[WebDriver, None, None]:
  137. """Get an instance of the browser open to the event_action app.
  138. Args:
  139. event_action: harness for TestEventAction app
  140. Yields:
  141. WebDriver instance.
  142. """
  143. assert event_action.app_instance is not None, "app is not running"
  144. driver = event_action.frontend()
  145. try:
  146. yield driver
  147. finally:
  148. driver.quit()
  149. @pytest.fixture()
  150. def token(event_action: AppHarness, driver: WebDriver) -> str:
  151. """Get the token associated with backend state.
  152. Args:
  153. event_action: harness for TestEventAction app.
  154. driver: WebDriver instance.
  155. Returns:
  156. The token visible in the driver browser.
  157. """
  158. assert event_action.app_instance is not None
  159. token_input = driver.find_element(By.ID, "token")
  160. assert token_input
  161. # wait for the backend connection to send the token
  162. token = event_action.poll_for_value(token_input)
  163. assert token is not None
  164. return token
  165. @pytest.fixture()
  166. def poll_for_order(
  167. event_action: AppHarness, token: str
  168. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  169. """Poll for the order list to match the expected order.
  170. Args:
  171. event_action: harness for TestEventAction app.
  172. token: The token visible in the driver browser.
  173. Returns:
  174. An async function that polls for the order list to match the expected order.
  175. """
  176. async def _poll_for_order(exp_order: list[str]):
  177. async def _backend_state():
  178. return await event_action.get_state(token)
  179. async def _check():
  180. return (await _backend_state()).order == exp_order
  181. await AppHarness._poll_for_async(_check)
  182. assert (await _backend_state()).order == exp_order
  183. return _poll_for_order
  184. @pytest.mark.parametrize(
  185. ("element_id", "exp_order"),
  186. [
  187. ("btn-no-events", ["on_click:outer"]),
  188. ("btn-stop-prop-only", []),
  189. ("btn-click-event", ["on_click:no_event_actions", "on_click:outer"]),
  190. ("btn-click-stop-propagation", ["on_click:stop_propagation"]),
  191. ("btn-click-stop-propagation2", ["on_click2"]),
  192. ("btn-click-event2", ["on_click2", "on_click:outer"]),
  193. ("link", ["on_click:link_no_event_actions", "on_click:outer"]),
  194. ("link-stop-propagation", ["on_click:link_stop_propagation"]),
  195. ("link-prevent-default", ["on_click:link_prevent_default", "on_click:outer"]),
  196. ("link-prevent-default-only", ["on_click:outer"]),
  197. ("link-stop-propagation-prevent-default", ["on_click:link_both"]),
  198. (
  199. "custom-stop-propagation",
  200. ["on_click:custom-stop-propagation", "on_click:outer"],
  201. ),
  202. (
  203. "custom-prevent-default",
  204. ["on_click:custom-prevent-default", "on_click:outer"],
  205. ),
  206. ],
  207. )
  208. @pytest.mark.usefixtures("token")
  209. @pytest.mark.asyncio
  210. async def test_event_actions(
  211. driver: WebDriver,
  212. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  213. element_id: str,
  214. exp_order: list[str],
  215. ):
  216. """Click links and buttons and assert on fired events.
  217. Args:
  218. driver: WebDriver instance.
  219. poll_for_order: function that polls for the order list to match the expected order.
  220. element_id: The id of the element to click.
  221. exp_order: The expected order of events.
  222. """
  223. el = driver.find_element(By.ID, element_id)
  224. assert el
  225. prev_url = driver.current_url
  226. el.click()
  227. if "on_click:outer" not in exp_order:
  228. # really make sure the outer event is not fired
  229. await asyncio.sleep(0.5)
  230. await poll_for_order(exp_order)
  231. if element_id.startswith("link") and "prevent-default" not in element_id:
  232. assert driver.current_url != prev_url
  233. else:
  234. assert driver.current_url == prev_url