test_event_actions.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385
  1. """Ensure stopPropagation and preventDefault work as expected."""
  2. from __future__ import annotations
  3. import asyncio
  4. import time
  5. from collections.abc import Callable, Coroutine, Generator
  6. import pytest
  7. from selenium.webdriver.common.by import By
  8. from selenium.webdriver.common.keys import Keys
  9. from selenium.webdriver.support import expected_conditions as EC
  10. from selenium.webdriver.support.wait import WebDriverWait
  11. from reflex.testing import AppHarness, WebDriver
  12. def TestEventAction():
  13. """App for testing event_actions."""
  14. from typing import Any
  15. import reflex as rx
  16. class EventActionState(rx.State):
  17. order: list[str]
  18. def on_click(self, ev):
  19. self.order.append(f"on_click:{ev}")
  20. @rx.event
  21. def on_click2(self):
  22. self.order.append("on_click2")
  23. def on_click_throttle(self):
  24. self.order.append("on_click_throttle")
  25. def on_click_debounce(self):
  26. self.order.append("on_click_debounce")
  27. @rx.event
  28. def on_submit(self, form_data: dict[str, Any]):
  29. self.order.append("on_submit")
  30. class EventFiringComponent(rx.Component):
  31. """A component that fires onClick event without passing DOM event."""
  32. tag = "EventFiringComponent"
  33. def _get_custom_code(self) -> str | None:
  34. return """
  35. function EventFiringComponent(props) {
  36. return (
  37. <div id={props.id} onClick={(e) => props.onClick("foo")}>
  38. Event Firing Component
  39. </div>
  40. )
  41. }"""
  42. def get_event_triggers(self):
  43. return {"on_click": lambda: []}
  44. def index():
  45. return rx.vstack(
  46. rx.input(
  47. value=EventActionState.router.session.client_token,
  48. is_read_only=True,
  49. id="token",
  50. ),
  51. rx.button("No events", id="btn-no-events"),
  52. rx.button(
  53. "Stop Prop Only",
  54. id="btn-stop-prop-only",
  55. on_click=rx.stop_propagation,
  56. ),
  57. rx.button(
  58. "Click event",
  59. on_click=EventActionState.on_click("no_event_actions"), # pyright: ignore [reportCallIssue]
  60. id="btn-click-event",
  61. ),
  62. rx.button(
  63. "Click stop propagation",
  64. on_click=EventActionState.on_click("stop_propagation").stop_propagation, # pyright: ignore [reportCallIssue]
  65. id="btn-click-stop-propagation",
  66. ),
  67. rx.button(
  68. "Click stop propagation2",
  69. on_click=EventActionState.on_click2.stop_propagation,
  70. id="btn-click-stop-propagation2",
  71. ),
  72. rx.button(
  73. "Click event 2",
  74. on_click=EventActionState.on_click2,
  75. id="btn-click-event2",
  76. ),
  77. rx.link(
  78. "Link",
  79. href="#",
  80. on_click=EventActionState.on_click("link_no_event_actions"), # pyright: ignore [reportCallIssue]
  81. id="link",
  82. ),
  83. rx.link(
  84. "Link Stop Propagation",
  85. href="#",
  86. on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue]
  87. "link_stop_propagation"
  88. ).stop_propagation,
  89. id="link-stop-propagation",
  90. ),
  91. rx.link(
  92. "Link Prevent Default Only",
  93. href="/invalid",
  94. on_click=rx.prevent_default,
  95. id="link-prevent-default-only",
  96. ),
  97. rx.link(
  98. "Link Prevent Default",
  99. href="/invalid",
  100. on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue]
  101. "link_prevent_default"
  102. ).prevent_default,
  103. id="link-prevent-default",
  104. ),
  105. rx.link(
  106. "Link Both",
  107. href="/invalid",
  108. on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue]
  109. "link_both"
  110. ).stop_propagation.prevent_default,
  111. id="link-stop-propagation-prevent-default",
  112. ),
  113. EventFiringComponent.create(
  114. id="custom-stop-propagation",
  115. on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue]
  116. "custom-stop-propagation"
  117. ).stop_propagation,
  118. ),
  119. EventFiringComponent.create(
  120. id="custom-prevent-default",
  121. on_click=EventActionState.on_click( # pyright: ignore [reportCallIssue]
  122. "custom-prevent-default"
  123. ).prevent_default,
  124. ),
  125. rx.button(
  126. "Throttle",
  127. id="btn-throttle",
  128. on_click=lambda: EventActionState.on_click_throttle.throttle( # pyright: ignore [reportFunctionMemberAccess]
  129. 200
  130. ).stop_propagation,
  131. ),
  132. rx.button(
  133. "Debounce",
  134. id="btn-debounce",
  135. on_click=EventActionState.on_click_debounce.debounce( # pyright: ignore [reportFunctionMemberAccess]
  136. 200
  137. ).stop_propagation,
  138. ),
  139. rx.list( # pyright: ignore [reportAttributeAccessIssue]
  140. rx.foreach(
  141. EventActionState.order,
  142. rx.list_item,
  143. ),
  144. ),
  145. on_click=EventActionState.on_click("outer"), # pyright: ignore [reportCallIssue]
  146. ), rx.form(
  147. rx.dialog.root(
  148. rx.dialog.trigger(
  149. rx.button("Open Dialog", type="button", id="btn-dialog"),
  150. on_click=rx.stop_propagation,
  151. ),
  152. rx.dialog.content(
  153. rx.dialog.close(
  154. rx.form(
  155. rx.button("Submit", id="btn-submit"),
  156. on_submit=EventActionState.on_submit.stop_propagation, # pyright: ignore [reportCallIssue]
  157. ),
  158. ),
  159. ),
  160. ),
  161. on_submit=EventActionState.on_submit, # pyright: ignore [reportCallIssue]
  162. )
  163. app = rx.App()
  164. app.add_page(index)
  165. @pytest.fixture(scope="module")
  166. def event_action(tmp_path_factory) -> Generator[AppHarness, None, None]:
  167. """Start TestEventAction app at tmp_path via AppHarness.
  168. Args:
  169. tmp_path_factory: pytest tmp_path_factory fixture
  170. Yields:
  171. running AppHarness instance
  172. """
  173. with AppHarness.create(
  174. root=tmp_path_factory.mktemp("event_action"),
  175. app_source=TestEventAction,
  176. ) as harness:
  177. yield harness
  178. @pytest.fixture
  179. def driver(event_action: AppHarness) -> Generator[WebDriver, None, None]:
  180. """Get an instance of the browser open to the event_action app.
  181. Args:
  182. event_action: harness for TestEventAction app
  183. Yields:
  184. WebDriver instance.
  185. """
  186. assert event_action.app_instance is not None, "app is not running"
  187. driver = event_action.frontend()
  188. try:
  189. yield driver
  190. finally:
  191. driver.quit()
  192. @pytest.fixture()
  193. def token(event_action: AppHarness, driver: WebDriver) -> str:
  194. """Get the token associated with backend state.
  195. Args:
  196. event_action: harness for TestEventAction app.
  197. driver: WebDriver instance.
  198. Returns:
  199. The token visible in the driver browser.
  200. """
  201. assert event_action.app_instance is not None
  202. token_input = driver.find_element(By.ID, "token")
  203. assert token_input
  204. # wait for the backend connection to send the token
  205. token = event_action.poll_for_value(token_input)
  206. assert token is not None
  207. return token
  208. @pytest.fixture()
  209. def poll_for_order(
  210. event_action: AppHarness, token: str
  211. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  212. """Poll for the order list to match the expected order.
  213. Args:
  214. event_action: harness for TestEventAction app.
  215. token: The token visible in the driver browser.
  216. Returns:
  217. An async function that polls for the order list to match the expected order.
  218. """
  219. state_name = event_action.get_state_name("_event_action_state")
  220. state_full_name = event_action.get_full_state_name(["_event_action_state"])
  221. async def _poll_for_order(exp_order: list[str]):
  222. async def _backend_state():
  223. return await event_action.get_state(f"{token}_{state_full_name}")
  224. async def _check():
  225. return (await _backend_state()).substates[state_name].order == exp_order
  226. await AppHarness._poll_for_async(_check)
  227. assert (await _backend_state()).substates[state_name].order == exp_order
  228. return _poll_for_order
  229. @pytest.mark.parametrize(
  230. ("element_id", "exp_order"),
  231. [
  232. ("btn-no-events", ["on_click:outer"]),
  233. ("btn-stop-prop-only", []),
  234. ("btn-click-event", ["on_click:no_event_actions", "on_click:outer"]),
  235. ("btn-click-stop-propagation", ["on_click:stop_propagation"]),
  236. ("btn-click-stop-propagation2", ["on_click2"]),
  237. ("btn-click-event2", ["on_click2", "on_click:outer"]),
  238. ("link", ["on_click:link_no_event_actions", "on_click:outer"]),
  239. ("link-stop-propagation", ["on_click:link_stop_propagation"]),
  240. ("link-prevent-default", ["on_click:link_prevent_default", "on_click:outer"]),
  241. ("link-prevent-default-only", ["on_click:outer"]),
  242. ("link-stop-propagation-prevent-default", ["on_click:link_both"]),
  243. (
  244. "custom-stop-propagation",
  245. ["on_click:custom-stop-propagation", "on_click:outer"],
  246. ),
  247. (
  248. "custom-prevent-default",
  249. ["on_click:custom-prevent-default", "on_click:outer"],
  250. ),
  251. ],
  252. )
  253. @pytest.mark.usefixtures("token")
  254. @pytest.mark.asyncio
  255. async def test_event_actions(
  256. driver: WebDriver,
  257. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  258. element_id: str,
  259. exp_order: list[str],
  260. ):
  261. """Click links and buttons and assert on fired events.
  262. Args:
  263. driver: WebDriver instance.
  264. poll_for_order: function that polls for the order list to match the expected order.
  265. element_id: The id of the element to click.
  266. exp_order: The expected order of events.
  267. """
  268. el = driver.find_element(By.ID, element_id)
  269. assert el
  270. prev_url = driver.current_url
  271. el.click()
  272. if "on_click:outer" not in exp_order:
  273. # really make sure the outer event is not fired
  274. await asyncio.sleep(0.5)
  275. await poll_for_order(exp_order)
  276. if element_id.startswith("link") and "prevent-default" not in element_id:
  277. assert driver.current_url != prev_url
  278. else:
  279. assert driver.current_url == prev_url
  280. @pytest.mark.usefixtures("token")
  281. @pytest.mark.asyncio
  282. async def test_event_actions_throttle_debounce(
  283. driver: WebDriver,
  284. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  285. ):
  286. """Click buttons with debounce and throttle and assert on fired events.
  287. Args:
  288. driver: WebDriver instance.
  289. poll_for_order: function that polls for the order list to match the expected order.
  290. """
  291. btn_throttle = driver.find_element(By.ID, "btn-throttle")
  292. assert btn_throttle
  293. btn_debounce = driver.find_element(By.ID, "btn-debounce")
  294. assert btn_debounce
  295. exp_events = 10
  296. throttle_duration = exp_events * 0.2 # 200ms throttle
  297. throttle_start = time.time()
  298. while time.time() - throttle_start < throttle_duration:
  299. btn_throttle.click()
  300. btn_debounce.click()
  301. try:
  302. await poll_for_order(["on_click_throttle"] * exp_events + ["on_click_debounce"])
  303. except AssertionError:
  304. # Sometimes the last event gets throttled due to race, this is okay.
  305. await poll_for_order(
  306. ["on_click_throttle"] * (exp_events - 1) + ["on_click_debounce"]
  307. )
  308. @pytest.mark.usefixtures("token")
  309. @pytest.mark.asyncio
  310. async def test_event_actions_dialog_form_in_form(
  311. driver: WebDriver,
  312. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  313. ):
  314. """Click links and buttons and assert on fired events.
  315. Args:
  316. driver: WebDriver instance.
  317. poll_for_order: function that polls for the order list to match the expected order.
  318. """
  319. open_dialog_id = "btn-dialog"
  320. submit_button_id = "btn-submit"
  321. wait = WebDriverWait(driver, 10)
  322. driver.find_element(By.ID, open_dialog_id).click()
  323. el = wait.until(EC.element_to_be_clickable((By.ID, submit_button_id)))
  324. el.click() # pyright: ignore[reportAttributeAccessIssue]
  325. el.send_keys(Keys.ESCAPE) # pyright: ignore[reportAttributeAccessIssue]
  326. btn_no_events = wait.until(EC.element_to_be_clickable((By.ID, "btn-no-events")))
  327. btn_no_events.click()
  328. await poll_for_order(["on_submit", "on_click:outer"])