test_event_actions.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  1. """Ensure stopPropagation and preventDefault work as expected."""
  2. from typing import Callable, Coroutine, Generator
  3. import pytest
  4. from selenium.webdriver.common.by import By
  5. from reflex.testing import AppHarness, WebDriver
  6. def TestEventAction():
  7. """App for testing event_actions."""
  8. import reflex as rx
  9. class EventActionState(rx.State):
  10. order: list[str]
  11. def on_click(self, ev):
  12. self.order.append(f"on_click:{ev}")
  13. def on_click2(self):
  14. self.order.append("on_click2")
  15. @rx.var
  16. def token(self) -> str:
  17. return self.get_token()
  18. def index():
  19. return rx.vstack(
  20. rx.input(value=EventActionState.token, is_read_only=True, id="token"),
  21. rx.button("No events", id="btn-no-events"),
  22. rx.button(
  23. "Stop Prop Only",
  24. id="btn-stop-prop-only",
  25. on_click=rx.stop_propagation, # type: ignore
  26. ),
  27. rx.button(
  28. "Click event",
  29. on_click=EventActionState.on_click("no_event_actions"), # type: ignore
  30. id="btn-click-event",
  31. ),
  32. rx.button(
  33. "Click stop propagation",
  34. on_click=EventActionState.on_click("stop_propagation").stop_propagation, # type: ignore
  35. id="btn-click-stop-propagation",
  36. ),
  37. rx.button(
  38. "Click stop propagation2",
  39. on_click=EventActionState.on_click2.stop_propagation,
  40. id="btn-click-stop-propagation2",
  41. ),
  42. rx.button(
  43. "Click event 2",
  44. on_click=EventActionState.on_click2,
  45. id="btn-click-event2",
  46. ),
  47. rx.link(
  48. "Link",
  49. href="#",
  50. on_click=EventActionState.on_click("link_no_event_actions"), # type: ignore
  51. id="link",
  52. ),
  53. rx.link(
  54. "Link Stop Propagation",
  55. href="#",
  56. on_click=EventActionState.on_click( # type: ignore
  57. "link_stop_propagation"
  58. ).stop_propagation,
  59. id="link-stop-propagation",
  60. ),
  61. rx.link(
  62. "Link Prevent Default Only",
  63. href="/invalid",
  64. on_click=rx.prevent_default, # type: ignore
  65. id="link-prevent-default-only",
  66. ),
  67. rx.link(
  68. "Link Prevent Default",
  69. href="/invalid",
  70. on_click=EventActionState.on_click( # type: ignore
  71. "link_prevent_default"
  72. ).prevent_default,
  73. id="link-prevent-default",
  74. ),
  75. rx.link(
  76. "Link Both",
  77. href="/invalid",
  78. on_click=EventActionState.on_click( # type: ignore
  79. "link_both"
  80. ).stop_propagation.prevent_default,
  81. id="link-stop-propagation-prevent-default",
  82. ),
  83. rx.list(
  84. rx.foreach(
  85. EventActionState.order, # type: ignore
  86. rx.list_item,
  87. ),
  88. ),
  89. on_click=EventActionState.on_click("outer"), # type: ignore
  90. )
  91. app = rx.App(state=EventActionState)
  92. app.add_page(index)
  93. app.compile()
  94. @pytest.fixture(scope="session")
  95. def event_action(tmp_path_factory) -> Generator[AppHarness, None, None]:
  96. """Start TestEventAction app at tmp_path via AppHarness.
  97. Args:
  98. tmp_path_factory: pytest tmp_path_factory fixture
  99. Yields:
  100. running AppHarness instance
  101. """
  102. with AppHarness.create(
  103. root=tmp_path_factory.mktemp(f"event_action"),
  104. app_source=TestEventAction, # type: ignore
  105. ) as harness:
  106. yield harness
  107. @pytest.fixture
  108. def driver(event_action: AppHarness) -> Generator[WebDriver, None, None]:
  109. """Get an instance of the browser open to the event_action app.
  110. Args:
  111. event_action: harness for TestEventAction app
  112. Yields:
  113. WebDriver instance.
  114. """
  115. assert event_action.app_instance is not None, "app is not running"
  116. driver = event_action.frontend()
  117. try:
  118. yield driver
  119. finally:
  120. driver.quit()
  121. @pytest.fixture()
  122. def token(event_action: AppHarness, driver: WebDriver) -> str:
  123. """Get the token associated with backend state.
  124. Args:
  125. event_action: harness for TestEventAction app.
  126. driver: WebDriver instance.
  127. Returns:
  128. The token visible in the driver browser.
  129. """
  130. assert event_action.app_instance is not None
  131. token_input = driver.find_element(By.ID, "token")
  132. assert token_input
  133. # wait for the backend connection to send the token
  134. token = event_action.poll_for_value(token_input)
  135. assert token is not None
  136. return token
  137. @pytest.fixture()
  138. def poll_for_order(
  139. event_action: AppHarness, token: str
  140. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  141. """Poll for the order list to match the expected order.
  142. Args:
  143. event_action: harness for TestEventAction app.
  144. token: The token visible in the driver browser.
  145. Returns:
  146. An async function that polls for the order list to match the expected order.
  147. """
  148. async def _poll_for_order(exp_order: list[str]):
  149. async def _backend_state():
  150. return await event_action.get_state(token)
  151. async def _check():
  152. return (await _backend_state()).order == exp_order
  153. await AppHarness._poll_for_async(_check)
  154. assert (await _backend_state()).order == exp_order
  155. return _poll_for_order
  156. @pytest.mark.parametrize(
  157. ("element_id", "exp_order"),
  158. [
  159. ("btn-no-events", ["on_click:outer"]),
  160. ("btn-stop-prop-only", []),
  161. ("btn-click-event", ["on_click:no_event_actions", "on_click:outer"]),
  162. ("btn-click-stop-propagation", ["on_click:stop_propagation"]),
  163. ("btn-click-stop-propagation2", ["on_click2"]),
  164. ("btn-click-event2", ["on_click2", "on_click:outer"]),
  165. ("link", ["on_click:link_no_event_actions", "on_click:outer"]),
  166. ("link-stop-propagation", ["on_click:link_stop_propagation"]),
  167. ("link-prevent-default", ["on_click:link_prevent_default", "on_click:outer"]),
  168. ("link-prevent-default-only", ["on_click:outer"]),
  169. ("link-stop-propagation-prevent-default", ["on_click:link_both"]),
  170. ],
  171. )
  172. @pytest.mark.usefixtures("token")
  173. @pytest.mark.asyncio
  174. async def test_event_actions(
  175. driver: WebDriver,
  176. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  177. element_id: str,
  178. exp_order: list[str],
  179. ):
  180. """Click links and buttons and assert on fired events.
  181. Args:
  182. driver: WebDriver instance.
  183. poll_for_order: function that polls for the order list to match the expected order.
  184. element_id: The id of the element to click.
  185. exp_order: The expected order of events.
  186. """
  187. el = driver.find_element(By.ID, element_id)
  188. assert el
  189. prev_url = driver.current_url
  190. el.click()
  191. await poll_for_order(exp_order)
  192. if element_id.startswith("link") and "prevent-default" not in element_id:
  193. assert driver.current_url != prev_url
  194. else:
  195. assert driver.current_url == prev_url