1
0

test_event_actions.py 11 KB

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