test_dynamic_routes.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. def on_load(self):
  16. page_data = f"{self.router.page.path}-{self.page_id or 'no page id'}"
  17. print(f"on_load: {page_data}")
  18. self.order.append(page_data)
  19. def on_load_redir(self):
  20. query_params = self.router.page.params
  21. page_data = f"on_load_redir-{query_params}"
  22. print(f"on_load_redir: {page_data}")
  23. self.order.append(page_data)
  24. return rx.redirect(f"/page/{query_params['page_id']}")
  25. @rx.var
  26. def next_page(self) -> str:
  27. try:
  28. return str(int(self.page_id) + 1)
  29. except ValueError:
  30. return "0"
  31. def index():
  32. return rx.fragment(
  33. rx.input(
  34. value=DynamicState.router.session.client_token,
  35. read_only=True,
  36. id="token",
  37. ),
  38. rx.input(value=rx.State.page_id, read_only=True, id="page_id"), # type: ignore
  39. rx.input(
  40. value=DynamicState.router.page.raw_path,
  41. read_only=True,
  42. id="raw_path",
  43. ),
  44. rx.link("index", href="/", id="link_index"),
  45. rx.link("page_X", href="/static/x", id="link_page_x"),
  46. rx.link(
  47. "next",
  48. href="/page/" + DynamicState.next_page,
  49. id="link_page_next", # type: ignore
  50. ),
  51. rx.link("missing", href="/missing", id="link_missing"),
  52. rx.list( # type: ignore
  53. rx.foreach(
  54. DynamicState.order, # type: ignore
  55. lambda i: rx.list_item(rx.text(i)),
  56. ),
  57. ),
  58. )
  59. class ArgState(rx.State):
  60. """The app state."""
  61. @rx.var
  62. def arg(self) -> int:
  63. return int(self.arg_str or 0)
  64. class ArgSubState(ArgState):
  65. @rx.var(cache=True)
  66. def cached_arg(self) -> int:
  67. return self.arg
  68. @rx.var(cache=True)
  69. def cached_arg_str(self) -> str:
  70. return self.arg_str
  71. @rx.page(route="/arg/[arg_str]")
  72. def arg() -> rx.Component:
  73. return rx.vstack(
  74. rx.data_list.root(
  75. rx.data_list.item(
  76. rx.data_list.label("rx.State.arg_str (dynamic)"),
  77. rx.data_list.value(rx.State.arg_str, id="state-arg_str"), # type: ignore
  78. ),
  79. rx.data_list.item(
  80. rx.data_list.label("ArgState.arg_str (dynamic) (inherited)"),
  81. rx.data_list.value(ArgState.arg_str, id="argstate-arg_str"), # type: ignore
  82. ),
  83. rx.data_list.item(
  84. rx.data_list.label("ArgState.arg"),
  85. rx.data_list.value(ArgState.arg, id="argstate-arg"),
  86. ),
  87. rx.data_list.item(
  88. rx.data_list.label("ArgSubState.arg_str (dynamic) (inherited)"),
  89. rx.data_list.value(ArgSubState.arg_str, id="argsubstate-arg_str"), # type: ignore
  90. ),
  91. rx.data_list.item(
  92. rx.data_list.label("ArgSubState.arg (inherited)"),
  93. rx.data_list.value(ArgSubState.arg, id="argsubstate-arg"),
  94. ),
  95. rx.data_list.item(
  96. rx.data_list.label("ArgSubState.cached_arg"),
  97. rx.data_list.value(
  98. ArgSubState.cached_arg, id="argsubstate-cached_arg"
  99. ),
  100. ),
  101. rx.data_list.item(
  102. rx.data_list.label("ArgSubState.cached_arg_str"),
  103. rx.data_list.value(
  104. ArgSubState.cached_arg_str, id="argsubstate-cached_arg_str"
  105. ),
  106. ),
  107. ),
  108. rx.link("+", href=f"/arg/{ArgState.arg + 1}", id="next-page"),
  109. align="center",
  110. height="100vh",
  111. )
  112. @rx.page(route="/redirect-page/[page_id]", on_load=DynamicState.on_load_redir) # type: ignore
  113. def redirect_page():
  114. return rx.fragment(rx.text("redirecting..."))
  115. app = rx.App(state=rx.State)
  116. app.add_page(index, route="/page/[page_id]", on_load=DynamicState.on_load) # type: ignore
  117. app.add_page(index, route="/static/x", on_load=DynamicState.on_load) # type: ignore
  118. app.add_page(index)
  119. app.add_custom_404_page(on_load=DynamicState.on_load) # type: ignore
  120. @pytest.fixture(scope="module")
  121. def dynamic_route(
  122. app_harness_env: Type[AppHarness], tmp_path_factory
  123. ) -> Generator[AppHarness, None, None]:
  124. """Start DynamicRoute app at tmp_path via AppHarness.
  125. Args:
  126. app_harness_env: either AppHarness (dev) or AppHarnessProd (prod)
  127. tmp_path_factory: pytest tmp_path_factory fixture
  128. Yields:
  129. running AppHarness instance
  130. """
  131. with app_harness_env.create(
  132. root=tmp_path_factory.mktemp("dynamic_route"),
  133. app_name=f"dynamicroute_{app_harness_env.__name__.lower()}",
  134. app_source=DynamicRoute, # type: ignore
  135. ) as harness:
  136. yield harness
  137. @pytest.fixture
  138. def driver(dynamic_route: AppHarness) -> Generator[WebDriver, None, None]:
  139. """Get an instance of the browser open to the dynamic_route app.
  140. Args:
  141. dynamic_route: harness for DynamicRoute app
  142. Yields:
  143. WebDriver instance.
  144. """
  145. assert dynamic_route.app_instance is not None, "app is not running"
  146. driver = dynamic_route.frontend()
  147. try:
  148. yield driver
  149. finally:
  150. driver.quit()
  151. @pytest.fixture()
  152. def token(dynamic_route: AppHarness, driver: WebDriver) -> str:
  153. """Get the token associated with backend state.
  154. Args:
  155. dynamic_route: harness for DynamicRoute app.
  156. driver: WebDriver instance.
  157. Returns:
  158. The token visible in the driver browser.
  159. """
  160. assert dynamic_route.app_instance is not None
  161. token_input = driver.find_element(By.ID, "token")
  162. assert token_input
  163. # wait for the backend connection to send the token
  164. token = dynamic_route.poll_for_value(token_input)
  165. assert token is not None
  166. return token
  167. @pytest.fixture()
  168. def poll_for_order(
  169. dynamic_route: AppHarness, token: str
  170. ) -> Callable[[list[str]], Coroutine[None, None, None]]:
  171. """Poll for the order list to match the expected order.
  172. Args:
  173. dynamic_route: harness for DynamicRoute app.
  174. token: The token visible in the driver browser.
  175. Returns:
  176. An async function that polls for the order list to match the expected order.
  177. """
  178. dynamic_state_name = dynamic_route.get_state_name("_dynamic_state")
  179. dynamic_state_full_name = dynamic_route.get_full_state_name(["_dynamic_state"])
  180. async def _poll_for_order(exp_order: list[str]):
  181. async def _backend_state():
  182. return await dynamic_route.get_state(f"{token}_{dynamic_state_full_name}")
  183. async def _check():
  184. return (await _backend_state()).substates[
  185. dynamic_state_name
  186. ].order == exp_order
  187. await AppHarness._poll_for_async(_check, timeout=60)
  188. assert (
  189. list((await _backend_state()).substates[dynamic_state_name].order)
  190. == exp_order
  191. )
  192. return _poll_for_order
  193. @pytest.mark.asyncio
  194. async def test_on_load_navigate(
  195. dynamic_route: AppHarness,
  196. driver: WebDriver,
  197. token: str,
  198. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  199. ):
  200. """Click links to navigate between dynamic pages with on_load event.
  201. Args:
  202. dynamic_route: harness for DynamicRoute app.
  203. driver: WebDriver instance.
  204. token: The token visible in the driver browser.
  205. poll_for_order: function that polls for the order list to match the expected order.
  206. """
  207. dynamic_state_full_name = dynamic_route.get_full_state_name(["_dynamic_state"])
  208. assert dynamic_route.app_instance is not None
  209. is_prod = isinstance(dynamic_route, AppHarnessProd)
  210. link = driver.find_element(By.ID, "link_page_next")
  211. assert link
  212. exp_order = [f"/page/[page_id]-{ix}" for ix in range(10)]
  213. # click the link a few times
  214. for ix in range(10):
  215. # wait for navigation, then assert on url
  216. with poll_for_navigation(driver):
  217. link.click()
  218. assert urlsplit(driver.current_url).path == f"/page/{ix}/"
  219. link = driver.find_element(By.ID, "link_page_next")
  220. page_id_input = driver.find_element(By.ID, "page_id")
  221. raw_path_input = driver.find_element(By.ID, "raw_path")
  222. assert link
  223. assert page_id_input
  224. assert dynamic_route.poll_for_value(
  225. page_id_input, exp_not_equal=str(ix - 1)
  226. ) == str(ix)
  227. assert dynamic_route.poll_for_value(raw_path_input) == f"/page/{ix}/"
  228. await poll_for_order(exp_order)
  229. # manually load the next page to trigger client side routing in prod mode
  230. if is_prod:
  231. exp_order += ["/404-no page id"]
  232. exp_order += ["/page/[page_id]-10"]
  233. with poll_for_navigation(driver):
  234. driver.get(f"{dynamic_route.frontend_url}/page/10/")
  235. await poll_for_order(exp_order)
  236. # make sure internal nav still hydrates after redirect
  237. exp_order += ["/page/[page_id]-11"]
  238. link = driver.find_element(By.ID, "link_page_next")
  239. with poll_for_navigation(driver):
  240. link.click()
  241. await poll_for_order(exp_order)
  242. # load same page with a query param and make sure it passes through
  243. if is_prod:
  244. exp_order += ["/404-no page id"]
  245. exp_order += ["/page/[page_id]-11"]
  246. with poll_for_navigation(driver):
  247. driver.get(f"{driver.current_url}?foo=bar")
  248. await poll_for_order(exp_order)
  249. assert (
  250. await dynamic_route.get_state(f"{token}_{dynamic_state_full_name}")
  251. ).router.page.params["foo"] == "bar"
  252. # hit a 404 and ensure we still hydrate
  253. exp_order += ["/404-no page id"]
  254. with poll_for_navigation(driver):
  255. driver.get(f"{dynamic_route.frontend_url}/missing")
  256. await poll_for_order(exp_order)
  257. # browser nav should still trigger hydration
  258. if is_prod:
  259. exp_order += ["/404-no page id"]
  260. exp_order += ["/page/[page_id]-11"]
  261. with poll_for_navigation(driver):
  262. driver.back()
  263. await poll_for_order(exp_order)
  264. # next/link to a 404 and ensure we still hydrate
  265. exp_order += ["/404-no page id"]
  266. link = driver.find_element(By.ID, "link_missing")
  267. with poll_for_navigation(driver):
  268. link.click()
  269. await poll_for_order(exp_order)
  270. # hit a page that redirects back to dynamic page
  271. if is_prod:
  272. exp_order += ["/404-no page id"]
  273. exp_order += ["on_load_redir-{'foo': 'bar', 'page_id': '0'}", "/page/[page_id]-0"]
  274. with poll_for_navigation(driver):
  275. driver.get(f"{dynamic_route.frontend_url}/redirect-page/0/?foo=bar")
  276. await poll_for_order(exp_order)
  277. # should have redirected back to page 0
  278. assert urlsplit(driver.current_url).path == "/page/0/"
  279. @pytest.mark.asyncio
  280. async def test_on_load_navigate_non_dynamic(
  281. dynamic_route: AppHarness,
  282. driver: WebDriver,
  283. poll_for_order: Callable[[list[str]], Coroutine[None, None, None]],
  284. ):
  285. """Click links to navigate between static pages with on_load event.
  286. Args:
  287. dynamic_route: harness for DynamicRoute app.
  288. driver: WebDriver instance.
  289. poll_for_order: function that polls for the order list to match the expected order.
  290. """
  291. assert dynamic_route.app_instance is not None
  292. link = driver.find_element(By.ID, "link_page_x")
  293. assert link
  294. with poll_for_navigation(driver):
  295. link.click()
  296. assert urlsplit(driver.current_url).path == "/static/x/"
  297. await poll_for_order(["/static/x-no page id"])
  298. # go back to the index and navigate back to the static route
  299. link = driver.find_element(By.ID, "link_index")
  300. with poll_for_navigation(driver):
  301. link.click()
  302. assert urlsplit(driver.current_url).path == "/"
  303. link = driver.find_element(By.ID, "link_page_x")
  304. with poll_for_navigation(driver):
  305. link.click()
  306. assert urlsplit(driver.current_url).path == "/static/x/"
  307. await poll_for_order(["/static/x-no page id", "/static/x-no page id"])
  308. @pytest.mark.asyncio
  309. async def test_render_dynamic_arg(
  310. dynamic_route: AppHarness,
  311. driver: WebDriver,
  312. ):
  313. """Assert that dynamic arg var is rendered correctly in different contexts.
  314. Args:
  315. dynamic_route: harness for DynamicRoute app.
  316. driver: WebDriver instance.
  317. """
  318. assert dynamic_route.app_instance is not None
  319. with poll_for_navigation(driver):
  320. driver.get(f"{dynamic_route.frontend_url}/arg/0")
  321. def assert_content(expected: str, expect_not: str):
  322. ids = [
  323. "state-arg_str",
  324. "argstate-arg",
  325. "argstate-arg_str",
  326. "argsubstate-arg_str",
  327. "argsubstate-arg",
  328. "argsubstate-cached_arg",
  329. "argsubstate-cached_arg_str",
  330. ]
  331. for id in ids:
  332. el = driver.find_element(By.ID, id)
  333. assert el
  334. assert (
  335. dynamic_route.poll_for_content(el, exp_not_equal=expect_not) == expected
  336. )
  337. assert_content("0", "")
  338. next_page_link = driver.find_element(By.ID, "next-page")
  339. assert next_page_link
  340. with poll_for_navigation(driver):
  341. next_page_link.click()
  342. assert driver.current_url == f"{dynamic_route.frontend_url}/arg/1/"
  343. assert_content("1", "0")
  344. next_page_link = driver.find_element(By.ID, "next-page")
  345. assert next_page_link
  346. with poll_for_navigation(driver):
  347. next_page_link.click()
  348. assert driver.current_url == f"{dynamic_route.frontend_url}/arg/2/"
  349. assert_content("2", "1")