test_client_storage.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543
  1. """Integration tests for client side storage."""
  2. from __future__ import annotations
  3. import time
  4. from typing import Generator
  5. import pytest
  6. from selenium.webdriver.common.by import By
  7. from selenium.webdriver.remote.webdriver import WebDriver
  8. from reflex.testing import AppHarness
  9. from . import utils
  10. def ClientSide():
  11. """App for testing client-side state."""
  12. import reflex as rx
  13. class ClientSideState(rx.State):
  14. state_var: str = ""
  15. input_value: str = ""
  16. class ClientSideSubState(ClientSideState):
  17. # cookies with default settings
  18. c1: str = rx.Cookie()
  19. c2: rx.Cookie = "c2 default" # type: ignore
  20. # cookies with custom settings
  21. c3: str = rx.Cookie(max_age=2) # expires after 2 second
  22. c4: rx.Cookie = rx.Cookie(same_site="strict")
  23. c5: str = rx.Cookie(path="/foo/") # only accessible on `/foo/`
  24. c6: str = rx.Cookie(name="c6")
  25. c7: str = rx.Cookie("c7 default")
  26. # local storage with default settings
  27. l1: str = rx.LocalStorage()
  28. l2: rx.LocalStorage = "l2 default" # type: ignore
  29. # local storage with custom settings
  30. l3: str = rx.LocalStorage(name="l3")
  31. l4: str = rx.LocalStorage("l4 default")
  32. def set_var(self):
  33. setattr(self, self.state_var, self.input_value)
  34. self.state_var = self.input_value = ""
  35. class ClientSideSubSubState(ClientSideSubState):
  36. c1s: str = rx.Cookie()
  37. l1s: str = rx.LocalStorage()
  38. def set_var(self):
  39. setattr(self, self.state_var, self.input_value)
  40. self.state_var = self.input_value = ""
  41. def index():
  42. return rx.fragment(
  43. rx.input(
  44. value=ClientSideState.router.session.client_token,
  45. is_read_only=True,
  46. id="token",
  47. ),
  48. rx.input(
  49. placeholder="state var",
  50. value=ClientSideState.state_var,
  51. on_change=ClientSideState.set_state_var, # type: ignore
  52. id="state_var",
  53. ),
  54. rx.input(
  55. placeholder="input value",
  56. value=ClientSideState.input_value,
  57. on_change=ClientSideState.set_input_value, # type: ignore
  58. id="input_value",
  59. ),
  60. rx.button(
  61. "Set ClientSideSubState",
  62. on_click=ClientSideSubState.set_var,
  63. id="set_sub_state",
  64. ),
  65. rx.button(
  66. "Set ClientSideSubSubState",
  67. on_click=ClientSideSubSubState.set_var,
  68. id="set_sub_sub_state",
  69. ),
  70. rx.box(ClientSideSubState.c1, id="c1"),
  71. rx.box(ClientSideSubState.c2, id="c2"),
  72. rx.box(ClientSideSubState.c3, id="c3"),
  73. rx.box(ClientSideSubState.c4, id="c4"),
  74. rx.box(ClientSideSubState.c5, id="c5"),
  75. rx.box(ClientSideSubState.c6, id="c6"),
  76. rx.box(ClientSideSubState.c7, id="c7"),
  77. rx.box(ClientSideSubState.l1, id="l1"),
  78. rx.box(ClientSideSubState.l2, id="l2"),
  79. rx.box(ClientSideSubState.l3, id="l3"),
  80. rx.box(ClientSideSubState.l4, id="l4"),
  81. rx.box(ClientSideSubSubState.c1s, id="c1s"),
  82. rx.box(ClientSideSubSubState.l1s, id="l1s"),
  83. )
  84. app = rx.App(state=rx.State)
  85. app.add_page(index)
  86. app.add_page(index, route="/foo")
  87. @pytest.fixture(scope="session")
  88. def client_side(tmp_path_factory) -> Generator[AppHarness, None, None]:
  89. """Start ClientSide app at tmp_path via AppHarness.
  90. Args:
  91. tmp_path_factory: pytest tmp_path_factory fixture
  92. Yields:
  93. running AppHarness instance
  94. """
  95. with AppHarness.create(
  96. root=tmp_path_factory.mktemp("client_side"),
  97. app_source=ClientSide, # type: ignore
  98. ) as harness:
  99. yield harness
  100. @pytest.fixture
  101. def driver(client_side: AppHarness) -> Generator[WebDriver, None, None]:
  102. """Get an instance of the browser open to the client_side app.
  103. Args:
  104. client_side: harness for ClientSide app
  105. Yields:
  106. WebDriver instance.
  107. """
  108. assert client_side.app_instance is not None, "app is not running"
  109. driver = client_side.frontend()
  110. try:
  111. yield driver
  112. finally:
  113. driver.quit()
  114. @pytest.fixture()
  115. def local_storage(driver: WebDriver) -> Generator[utils.LocalStorage, None, None]:
  116. """Get an instance of the local storage helper.
  117. Args:
  118. driver: WebDriver instance.
  119. Yields:
  120. Local storage helper.
  121. """
  122. ls = utils.LocalStorage(driver)
  123. yield ls
  124. ls.clear()
  125. @pytest.fixture(autouse=True)
  126. def delete_all_cookies(driver: WebDriver) -> Generator[None, None, None]:
  127. """Delete all cookies after each test.
  128. Args:
  129. driver: WebDriver instance.
  130. Yields:
  131. None
  132. """
  133. yield
  134. driver.delete_all_cookies()
  135. def cookie_info_map(driver: WebDriver) -> dict[str, dict[str, str]]:
  136. """Get a map of cookie names to cookie info.
  137. Args:
  138. driver: WebDriver instance.
  139. Returns:
  140. A map of cookie names to cookie info.
  141. """
  142. return {cookie_info["name"]: cookie_info for cookie_info in driver.get_cookies()}
  143. @pytest.mark.asyncio
  144. async def test_client_side_state(
  145. client_side: AppHarness, driver: WebDriver, local_storage: utils.LocalStorage
  146. ):
  147. """Test client side state.
  148. Args:
  149. client_side: harness for ClientSide app.
  150. driver: WebDriver instance.
  151. local_storage: Local storage helper.
  152. """
  153. assert client_side.app_instance is not None
  154. assert client_side.frontend_url is not None
  155. token_input = driver.find_element(By.ID, "token")
  156. assert token_input
  157. # wait for the backend connection to send the token
  158. token = client_side.poll_for_value(token_input)
  159. assert token is not None
  160. # get a reference to the cookie manipulation form
  161. state_var_input = driver.find_element(By.ID, "state_var")
  162. input_value_input = driver.find_element(By.ID, "input_value")
  163. set_sub_state_button = driver.find_element(By.ID, "set_sub_state")
  164. set_sub_sub_state_button = driver.find_element(By.ID, "set_sub_sub_state")
  165. # get a reference to all cookie and local storage elements
  166. c1 = driver.find_element(By.ID, "c1")
  167. c2 = driver.find_element(By.ID, "c2")
  168. c3 = driver.find_element(By.ID, "c3")
  169. c4 = driver.find_element(By.ID, "c4")
  170. c5 = driver.find_element(By.ID, "c5")
  171. c6 = driver.find_element(By.ID, "c6")
  172. c7 = driver.find_element(By.ID, "c7")
  173. l1 = driver.find_element(By.ID, "l1")
  174. l2 = driver.find_element(By.ID, "l2")
  175. l3 = driver.find_element(By.ID, "l3")
  176. l4 = driver.find_element(By.ID, "l4")
  177. c1s = driver.find_element(By.ID, "c1s")
  178. l1s = driver.find_element(By.ID, "l1s")
  179. # assert on defaults where present
  180. assert c1.text == ""
  181. assert c2.text == "c2 default"
  182. assert c3.text == ""
  183. assert c4.text == ""
  184. assert c5.text == ""
  185. assert c6.text == ""
  186. assert c7.text == "c7 default"
  187. assert l1.text == ""
  188. assert l2.text == "l2 default"
  189. assert l3.text == ""
  190. assert l4.text == "l4 default"
  191. assert c1s.text == ""
  192. assert l1s.text == ""
  193. # no cookies should be set yet!
  194. assert not driver.get_cookies()
  195. local_storage_items = local_storage.items()
  196. local_storage_items.pop("chakra-ui-color-mode", None)
  197. assert not local_storage_items
  198. # set some cookies and local storage values
  199. state_var_input.send_keys("c1")
  200. input_value_input.send_keys("c1 value")
  201. set_sub_state_button.click()
  202. state_var_input.send_keys("c2")
  203. input_value_input.send_keys("c2 value")
  204. set_sub_state_button.click()
  205. state_var_input.send_keys("c4")
  206. input_value_input.send_keys("c4 value")
  207. set_sub_state_button.click()
  208. state_var_input.send_keys("c5")
  209. input_value_input.send_keys("c5 value")
  210. set_sub_state_button.click()
  211. state_var_input.send_keys("c6")
  212. input_value_input.send_keys("c6 throwaway value")
  213. set_sub_state_button.click()
  214. state_var_input.send_keys("c6")
  215. input_value_input.send_keys("c6 value")
  216. set_sub_state_button.click()
  217. state_var_input.send_keys("c7")
  218. input_value_input.send_keys("c7 value")
  219. set_sub_state_button.click()
  220. state_var_input.send_keys("l1")
  221. input_value_input.send_keys("l1 value")
  222. set_sub_state_button.click()
  223. state_var_input.send_keys("l2")
  224. input_value_input.send_keys("l2 value")
  225. set_sub_state_button.click()
  226. state_var_input.send_keys("l3")
  227. input_value_input.send_keys("l3 value")
  228. set_sub_state_button.click()
  229. state_var_input.send_keys("l4")
  230. input_value_input.send_keys("l4 value")
  231. set_sub_state_button.click()
  232. state_var_input.send_keys("c1s")
  233. input_value_input.send_keys("c1s value")
  234. set_sub_sub_state_button.click()
  235. state_var_input.send_keys("l1s")
  236. input_value_input.send_keys("l1s value")
  237. set_sub_sub_state_button.click()
  238. exp_cookies = {
  239. "state.client_side_state.client_side_sub_state.c1": {
  240. "domain": "localhost",
  241. "httpOnly": False,
  242. "name": "state.client_side_state.client_side_sub_state.c1",
  243. "path": "/",
  244. "sameSite": "Lax",
  245. "secure": False,
  246. "value": "c1%20value",
  247. },
  248. "state.client_side_state.client_side_sub_state.c2": {
  249. "domain": "localhost",
  250. "httpOnly": False,
  251. "name": "state.client_side_state.client_side_sub_state.c2",
  252. "path": "/",
  253. "sameSite": "Lax",
  254. "secure": False,
  255. "value": "c2%20value",
  256. },
  257. "state.client_side_state.client_side_sub_state.c4": {
  258. "domain": "localhost",
  259. "httpOnly": False,
  260. "name": "state.client_side_state.client_side_sub_state.c4",
  261. "path": "/",
  262. "sameSite": "Strict",
  263. "secure": False,
  264. "value": "c4%20value",
  265. },
  266. "c6": {
  267. "domain": "localhost",
  268. "httpOnly": False,
  269. "name": "c6",
  270. "path": "/",
  271. "sameSite": "Lax",
  272. "secure": False,
  273. "value": "c6%20value",
  274. },
  275. "state.client_side_state.client_side_sub_state.c7": {
  276. "domain": "localhost",
  277. "httpOnly": False,
  278. "name": "state.client_side_state.client_side_sub_state.c7",
  279. "path": "/",
  280. "sameSite": "Lax",
  281. "secure": False,
  282. "value": "c7%20value",
  283. },
  284. "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.c1s": {
  285. "domain": "localhost",
  286. "httpOnly": False,
  287. "name": "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.c1s",
  288. "path": "/",
  289. "sameSite": "Lax",
  290. "secure": False,
  291. "value": "c1s%20value",
  292. },
  293. }
  294. AppHarness._poll_for(
  295. lambda: all(cookie_key in cookie_info_map(driver) for cookie_key in exp_cookies)
  296. )
  297. cookies = cookie_info_map(driver)
  298. for exp_cookie_key, exp_cookie_data in exp_cookies.items():
  299. assert cookies.pop(exp_cookie_key) == exp_cookie_data
  300. # assert all cookies have been popped for this page
  301. assert not cookies
  302. # Test cookie with expiry by itself to avoid timing flakiness
  303. state_var_input.send_keys("c3")
  304. input_value_input.send_keys("c3 value")
  305. set_sub_state_button.click()
  306. AppHarness._poll_for(
  307. lambda: "state.client_side_state.client_side_sub_state.c3"
  308. in cookie_info_map(driver)
  309. )
  310. c3_cookie = cookie_info_map(driver)[
  311. "state.client_side_state.client_side_sub_state.c3"
  312. ]
  313. assert c3_cookie.pop("expiry") is not None
  314. assert c3_cookie == {
  315. "domain": "localhost",
  316. "httpOnly": False,
  317. "name": "state.client_side_state.client_side_sub_state.c3",
  318. "path": "/",
  319. "sameSite": "Lax",
  320. "secure": False,
  321. "value": "c3%20value",
  322. }
  323. time.sleep(2) # wait for c3 to expire
  324. assert "state.client_side_state.client_side_sub_state.c3" not in cookie_info_map(
  325. driver
  326. )
  327. local_storage_items = local_storage.items()
  328. local_storage_items.pop("chakra-ui-color-mode", None)
  329. assert (
  330. local_storage_items.pop("state.client_side_state.client_side_sub_state.l1")
  331. == "l1 value"
  332. )
  333. assert (
  334. local_storage_items.pop("state.client_side_state.client_side_sub_state.l2")
  335. == "l2 value"
  336. )
  337. assert local_storage_items.pop("l3") == "l3 value"
  338. assert (
  339. local_storage_items.pop("state.client_side_state.client_side_sub_state.l4")
  340. == "l4 value"
  341. )
  342. assert (
  343. local_storage_items.pop(
  344. "state.client_side_state.client_side_sub_state.client_side_sub_sub_state.l1s"
  345. )
  346. == "l1s value"
  347. )
  348. assert not local_storage_items
  349. assert c1.text == "c1 value"
  350. assert c2.text == "c2 value"
  351. assert c3.text == "c3 value"
  352. assert c4.text == "c4 value"
  353. assert c5.text == "c5 value"
  354. assert c6.text == "c6 value"
  355. assert c7.text == "c7 value"
  356. assert l1.text == "l1 value"
  357. assert l2.text == "l2 value"
  358. assert l3.text == "l3 value"
  359. assert l4.text == "l4 value"
  360. assert c1s.text == "c1s value"
  361. assert l1s.text == "l1s value"
  362. # navigate to the /foo route
  363. with utils.poll_for_navigation(driver):
  364. driver.get(client_side.frontend_url + "/foo")
  365. # get new references to all cookie and local storage elements
  366. c1 = driver.find_element(By.ID, "c1")
  367. c2 = driver.find_element(By.ID, "c2")
  368. c3 = driver.find_element(By.ID, "c3")
  369. c4 = driver.find_element(By.ID, "c4")
  370. c5 = driver.find_element(By.ID, "c5")
  371. c6 = driver.find_element(By.ID, "c6")
  372. c7 = driver.find_element(By.ID, "c7")
  373. l1 = driver.find_element(By.ID, "l1")
  374. l2 = driver.find_element(By.ID, "l2")
  375. l3 = driver.find_element(By.ID, "l3")
  376. l4 = driver.find_element(By.ID, "l4")
  377. c1s = driver.find_element(By.ID, "c1s")
  378. l1s = driver.find_element(By.ID, "l1s")
  379. assert c1.text == "c1 value"
  380. assert c2.text == "c2 value"
  381. assert c3.text == "" # cookie expired so value removed from state
  382. assert c4.text == "c4 value"
  383. assert c5.text == "c5 value"
  384. assert c6.text == "c6 value"
  385. assert c7.text == "c7 value"
  386. assert l1.text == "l1 value"
  387. assert l2.text == "l2 value"
  388. assert l3.text == "l3 value"
  389. assert l4.text == "l4 value"
  390. assert c1s.text == "c1s value"
  391. assert l1s.text == "l1s value"
  392. # reset the backend state to force refresh from client storage
  393. async with client_side.modify_state(token) as state:
  394. state.reset()
  395. driver.refresh()
  396. # wait for the backend connection to send the token (again)
  397. token_input = driver.find_element(By.ID, "token")
  398. assert token_input
  399. token = client_side.poll_for_value(token_input)
  400. assert token is not None
  401. # get new references to all cookie and local storage elements (again)
  402. c1 = driver.find_element(By.ID, "c1")
  403. c2 = driver.find_element(By.ID, "c2")
  404. c3 = driver.find_element(By.ID, "c3")
  405. c4 = driver.find_element(By.ID, "c4")
  406. c5 = driver.find_element(By.ID, "c5")
  407. c6 = driver.find_element(By.ID, "c6")
  408. c7 = driver.find_element(By.ID, "c7")
  409. l1 = driver.find_element(By.ID, "l1")
  410. l2 = driver.find_element(By.ID, "l2")
  411. l3 = driver.find_element(By.ID, "l3")
  412. l4 = driver.find_element(By.ID, "l4")
  413. c1s = driver.find_element(By.ID, "c1s")
  414. l1s = driver.find_element(By.ID, "l1s")
  415. assert c1.text == "c1 value"
  416. assert c2.text == "c2 value"
  417. assert c3.text == "" # temporary cookie expired after reset state!
  418. assert c4.text == "c4 value"
  419. assert c5.text == "c5 value"
  420. assert c6.text == "c6 value"
  421. assert c7.text == "c7 value"
  422. assert l1.text == "l1 value"
  423. assert l2.text == "l2 value"
  424. assert l3.text == "l3 value"
  425. assert l4.text == "l4 value"
  426. assert c1s.text == "c1s value"
  427. assert l1s.text == "l1s value"
  428. # make sure c5 cookie shows up on the `/foo` route
  429. AppHarness._poll_for(
  430. lambda: "state.client_side_state.client_side_sub_state.c5"
  431. in cookie_info_map(driver)
  432. )
  433. assert cookie_info_map(driver)[
  434. "state.client_side_state.client_side_sub_state.c5"
  435. ] == {
  436. "domain": "localhost",
  437. "httpOnly": False,
  438. "name": "state.client_side_state.client_side_sub_state.c5",
  439. "path": "/foo/",
  440. "sameSite": "Lax",
  441. "secure": False,
  442. "value": "c5%20value",
  443. }
  444. # clear the cookie jar and local storage, ensure state reset to default
  445. driver.delete_all_cookies()
  446. local_storage.clear()
  447. # refresh the page to trigger re-hydrate
  448. driver.refresh()
  449. # wait for the backend connection to send the token (again)
  450. token_input = driver.find_element(By.ID, "token")
  451. assert token_input
  452. token = client_side.poll_for_value(token_input)
  453. assert token is not None
  454. # all values should be back to their defaults
  455. c1 = driver.find_element(By.ID, "c1")
  456. c2 = driver.find_element(By.ID, "c2")
  457. c3 = driver.find_element(By.ID, "c3")
  458. c4 = driver.find_element(By.ID, "c4")
  459. c5 = driver.find_element(By.ID, "c5")
  460. c6 = driver.find_element(By.ID, "c6")
  461. c7 = driver.find_element(By.ID, "c7")
  462. l1 = driver.find_element(By.ID, "l1")
  463. l2 = driver.find_element(By.ID, "l2")
  464. l3 = driver.find_element(By.ID, "l3")
  465. l4 = driver.find_element(By.ID, "l4")
  466. c1s = driver.find_element(By.ID, "c1s")
  467. l1s = driver.find_element(By.ID, "l1s")
  468. # assert on defaults where present
  469. assert c1.text == ""
  470. assert c2.text == "c2 default"
  471. assert c3.text == ""
  472. assert c4.text == ""
  473. assert c5.text == ""
  474. assert c6.text == ""
  475. assert c7.text == "c7 default"
  476. assert l1.text == ""
  477. assert l2.text == "l2 default"
  478. assert l3.text == ""
  479. assert l4.text == "l4 default"
  480. assert c1s.text == ""
  481. assert l1s.text == ""