1
0

test_dynamic_routes.py 14 KB

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