test_dynamic_routes.py 9.7 KB

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