test_dynamic_routes.py 9.5 KB

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