test_dynamic_routes.py 10 KB

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