test_dynamic_routes.py 9.1 KB

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