test_dynamic_routes.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. """Integration tests for dynamic route page behavior."""
  2. from __future__ import annotations
  3. from typing import Callable, Coroutine, Generator, Type
  4. from urllib.parse import urlsplit
  5. import pytest
  6. from selenium.webdriver.common.by import By
  7. from reflex.testing import AppHarness, AppHarnessProd, WebDriver
  8. from .utils import poll_for_navigation
  9. def DynamicRoute():
  10. """App for testing dynamic routes."""
  11. from typing import List
  12. import reflex as rx
  13. class DynamicState(rx.State):
  14. order: List[str] = []
  15. page_id: str = ""
  16. def on_load(self):
  17. self.order.append(f"{self.router.page.path}-{self.page_id or 'no page id'}")
  18. def on_load_redir(self):
  19. query_params = self.router.page.params
  20. self.order.append(f"on_load_redir-{query_params}")
  21. return rx.redirect(f"/page/{query_params['page_id']}")
  22. @rx.var
  23. def next_page(self) -> str:
  24. try:
  25. return str(int(self.page_id) + 1)
  26. except ValueError:
  27. return "0"
  28. def index():
  29. return rx.fragment(
  30. rx.chakra.input(
  31. value=DynamicState.router.session.client_token,
  32. is_read_only=True,
  33. id="token",
  34. ),
  35. rx.chakra.input(
  36. value=DynamicState.page_id, is_read_only=True, id="page_id"
  37. ),
  38. rx.chakra.input(
  39. value=DynamicState.router.page.raw_path,
  40. is_read_only=True,
  41. id="raw_path",
  42. ),
  43. rx.link("index", href="/", id="link_index"),
  44. rx.link("page_X", href="/static/x", id="link_page_x"),
  45. rx.link(
  46. "next",
  47. href="/page/" + DynamicState.next_page,
  48. id="link_page_next", # type: ignore
  49. ),
  50. rx.link("missing", href="/missing", id="link_missing"),
  51. rx.chakra.list(
  52. rx.foreach(
  53. DynamicState.order, # type: ignore
  54. lambda i: rx.chakra.list_item(rx.text(i)),
  55. ),
  56. ),
  57. )
  58. @rx.page(route="/redirect-page/[page_id]", on_load=DynamicState.on_load_redir) # type: ignore
  59. def redirect_page():
  60. return rx.fragment(rx.text("redirecting..."))
  61. app = rx.App(state=rx.State)
  62. app.add_page(index)
  63. app.add_page(index, route="/page/[page_id]", on_load=DynamicState.on_load) # type: ignore
  64. app.add_page(index, route="/static/x", on_load=DynamicState.on_load) # type: ignore
  65. app.add_custom_404_page(on_load=DynamicState.on_load) # type: ignore
  66. @pytest.fixture(scope="module")
  67. def dynamic_route(
  68. app_harness_env: Type[AppHarness], tmp_path_factory
  69. ) -> Generator[AppHarness, None, None]:
  70. """Start DynamicRoute app at tmp_path via AppHarness.
  71. Args:
  72. app_harness_env: either AppHarness (dev) or AppHarnessProd (prod)
  73. tmp_path_factory: pytest tmp_path_factory fixture
  74. Yields:
  75. running AppHarness instance
  76. """
  77. with app_harness_env.create(
  78. root=tmp_path_factory.mktemp(f"dynamic_route"),
  79. app_name=f"dynamicroute_{app_harness_env.__name__.lower()}",
  80. app_source=DynamicRoute, # type: ignore
  81. ) as harness:
  82. yield harness
  83. @pytest.fixture
  84. def driver(dynamic_route: AppHarness) -> Generator[WebDriver, None, None]:
  85. """Get an instance of the browser open to the dynamic_route app.
  86. Args:
  87. dynamic_route: harness for DynamicRoute app
  88. Yields:
  89. WebDriver instance.
  90. """
  91. assert dynamic_route.app_instance is not None, "app is not running"
  92. driver = dynamic_route.frontend()
  93. try:
  94. yield driver
  95. finally:
  96. driver.quit()
  97. @pytest.fixture()
  98. def token(dynamic_route: AppHarness, driver: WebDriver) -> str:
  99. """Get the token associated with backend state.
  100. Args:
  101. dynamic_route: harness for DynamicRoute app.
  102. driver: WebDriver instance.
  103. Returns:
  104. The token visible in the driver browser.
  105. """
  106. assert dynamic_route.app_instance is not None
  107. token_input = driver.find_element(By.ID, "token")
  108. assert token_input
  109. # wait for the backend connection to send the token
  110. token = dynamic_route.poll_for_value(token_input)
  111. assert token is not None
  112. return token
  113. @pytest.fixture()
  114. def poll_for_order(
  115. dynamic_route: AppHarness, token: str
  116. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  117. """Poll for the order list to match the expected order.
  118. Args:
  119. dynamic_route: harness for DynamicRoute app.
  120. token: The token visible in the driver browser.
  121. Returns:
  122. An async function that polls for the order list to match the expected order.
  123. """
  124. async def _poll_for_order(exp_order: list[str]):
  125. async def _backend_state():
  126. return await dynamic_route.get_state(f"{token}_state.dynamic_state")
  127. async def _check():
  128. return (await _backend_state()).substates[
  129. "dynamic_state"
  130. ].order == exp_order
  131. await AppHarness._poll_for_async(_check)
  132. assert (await _backend_state()).substates["dynamic_state"].order == exp_order
  133. return _poll_for_order
  134. @pytest.mark.asyncio
  135. async def test_on_load_navigate(
  136. dynamic_route: AppHarness,
  137. driver: WebDriver,
  138. token: str,
  139. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  140. ):
  141. """Click links to navigate between dynamic pages with on_load event.
  142. Args:
  143. dynamic_route: harness for DynamicRoute app.
  144. driver: WebDriver instance.
  145. token: The token visible in the driver browser.
  146. poll_for_order: function that polls for the order list to match the expected order.
  147. """
  148. assert dynamic_route.app_instance is not None
  149. is_prod = isinstance(dynamic_route, AppHarnessProd)
  150. link = driver.find_element(By.ID, "link_page_next")
  151. assert link
  152. exp_order = [f"/page/[page_id]-{ix}" for ix in range(10)]
  153. # click the link a few times
  154. for ix in range(10):
  155. # wait for navigation, then assert on url
  156. with poll_for_navigation(driver):
  157. link.click()
  158. assert urlsplit(driver.current_url).path == f"/page/{ix}/"
  159. link = driver.find_element(By.ID, "link_page_next")
  160. page_id_input = driver.find_element(By.ID, "page_id")
  161. raw_path_input = driver.find_element(By.ID, "raw_path")
  162. assert link
  163. assert page_id_input
  164. assert dynamic_route.poll_for_value(
  165. page_id_input, exp_not_equal=str(ix - 1)
  166. ) == str(ix)
  167. assert dynamic_route.poll_for_value(raw_path_input) == f"/page/{ix}/"
  168. await poll_for_order(exp_order)
  169. # manually load the next page to trigger client side routing in prod mode
  170. if is_prod:
  171. exp_order += ["/404-no page id"]
  172. exp_order += ["/page/[page_id]-10"]
  173. with poll_for_navigation(driver):
  174. driver.get(f"{dynamic_route.frontend_url}/page/10/")
  175. await poll_for_order(exp_order)
  176. # make sure internal nav still hydrates after redirect
  177. exp_order += ["/page/[page_id]-11"]
  178. link = driver.find_element(By.ID, "link_page_next")
  179. with poll_for_navigation(driver):
  180. link.click()
  181. await poll_for_order(exp_order)
  182. # load same page with a query param and make sure it passes through
  183. if is_prod:
  184. exp_order += ["/404-no page id"]
  185. exp_order += ["/page/[page_id]-11"]
  186. with poll_for_navigation(driver):
  187. driver.get(f"{driver.current_url}?foo=bar")
  188. await poll_for_order(exp_order)
  189. assert (
  190. await dynamic_route.get_state(f"{token}_state.dynamic_state")
  191. ).router.page.params["foo"] == "bar"
  192. # hit a 404 and ensure we still hydrate
  193. exp_order += ["/404-no page id"]
  194. with poll_for_navigation(driver):
  195. driver.get(f"{dynamic_route.frontend_url}/missing")
  196. await poll_for_order(exp_order)
  197. # browser nav should still trigger hydration
  198. if is_prod:
  199. exp_order += ["/404-no page id"]
  200. exp_order += ["/page/[page_id]-11"]
  201. with poll_for_navigation(driver):
  202. driver.back()
  203. await poll_for_order(exp_order)
  204. # next/link to a 404 and ensure we still hydrate
  205. exp_order += ["/404-no page id"]
  206. link = driver.find_element(By.ID, "link_missing")
  207. with poll_for_navigation(driver):
  208. link.click()
  209. await poll_for_order(exp_order)
  210. # hit a page that redirects back to dynamic page
  211. if is_prod:
  212. exp_order += ["/404-no page id"]
  213. exp_order += ["on_load_redir-{'foo': 'bar', 'page_id': '0'}", "/page/[page_id]-0"]
  214. with poll_for_navigation(driver):
  215. driver.get(f"{dynamic_route.frontend_url}/redirect-page/0/?foo=bar")
  216. await poll_for_order(exp_order)
  217. # should have redirected back to page 0
  218. assert urlsplit(driver.current_url).path == "/page/0/"
  219. @pytest.mark.asyncio
  220. async def test_on_load_navigate_non_dynamic(
  221. dynamic_route: AppHarness,
  222. driver: WebDriver,
  223. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  224. ):
  225. """Click links to navigate between static pages with on_load event.
  226. Args:
  227. dynamic_route: harness for DynamicRoute app.
  228. driver: WebDriver instance.
  229. poll_for_order: function that polls for the order list to match the expected order.
  230. """
  231. assert dynamic_route.app_instance is not None
  232. link = driver.find_element(By.ID, "link_page_x")
  233. assert link
  234. with poll_for_navigation(driver):
  235. link.click()
  236. assert urlsplit(driver.current_url).path == "/static/x/"
  237. await poll_for_order(["/static/x-no page id"])
  238. # go back to the index and navigate back to the static route
  239. link = driver.find_element(By.ID, "link_index")
  240. with poll_for_navigation(driver):
  241. link.click()
  242. assert urlsplit(driver.current_url).path == "/"
  243. link = driver.find_element(By.ID, "link_page_x")
  244. with poll_for_navigation(driver):
  245. link.click()
  246. assert urlsplit(driver.current_url).path == "/static/x/"
  247. await poll_for_order(["/static/x-no page id", "/static/x-no page id"])