test_event_actions.py 11 KB

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