test_event_actions.py 14 KB

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