test_dynamic_routes.py 14 KB

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