test_dynamic_routes.py 9.8 KB

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