test_event_actions.py 11 KB

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