test_app.py 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  1. from __future__ import annotations
  2. import io
  3. import os.path
  4. import unittest.mock
  5. import uuid
  6. from pathlib import Path
  7. from typing import Generator, List, Tuple, Type
  8. from unittest.mock import AsyncMock
  9. import pytest
  10. import sqlmodel
  11. from fastapi import UploadFile
  12. from starlette_admin.auth import AuthProvider
  13. from starlette_admin.contrib.sqla.admin import Admin
  14. from starlette_admin.contrib.sqla.view import ModelView
  15. import reflex.components.radix.themes as rdxt
  16. from reflex import AdminDash, constants
  17. from reflex.app import (
  18. App,
  19. ComponentCallable,
  20. default_overlay_component,
  21. process,
  22. upload,
  23. )
  24. from reflex.components import Box, Component, Cond, Fragment, Text
  25. from reflex.event import Event, get_hydrate_event
  26. from reflex.middleware import HydrateMiddleware
  27. from reflex.model import Model
  28. from reflex.state import RouterData, State, StateManagerRedis, StateUpdate
  29. from reflex.style import Style
  30. from reflex.utils import format
  31. from reflex.vars import ComputedVar
  32. from .conftest import chdir
  33. from .states import (
  34. ChildFileUploadState,
  35. FileStateBase1,
  36. FileUploadState,
  37. GenState,
  38. GrandChildFileUploadState,
  39. )
  40. class EmptyState(State):
  41. """An empty state."""
  42. pass
  43. @pytest.fixture
  44. def index_page():
  45. """An index page.
  46. Returns:
  47. The index page.
  48. """
  49. def index():
  50. return Box.create("Index")
  51. return index
  52. @pytest.fixture
  53. def about_page():
  54. """An about page.
  55. Returns:
  56. The about page.
  57. """
  58. def about():
  59. return Box.create("About")
  60. return about
  61. class ATestState(State):
  62. """A simple state for testing."""
  63. var: int
  64. @pytest.fixture()
  65. def test_state() -> Type[State]:
  66. """A default state.
  67. Returns:
  68. A default state.
  69. """
  70. return ATestState
  71. @pytest.fixture()
  72. def redundant_test_state() -> Type[State]:
  73. """A default state.
  74. Returns:
  75. A default state.
  76. """
  77. class RedundantTestState(State):
  78. var: int
  79. return RedundantTestState
  80. @pytest.fixture(scope="session")
  81. def test_model() -> Type[Model]:
  82. """A default model.
  83. Returns:
  84. A default model.
  85. """
  86. class TestModel(Model, table=True): # type: ignore
  87. pass
  88. return TestModel
  89. @pytest.fixture(scope="session")
  90. def test_model_auth() -> Type[Model]:
  91. """A default model.
  92. Returns:
  93. A default model.
  94. """
  95. class TestModelAuth(Model, table=True): # type: ignore
  96. """A test model with auth."""
  97. pass
  98. return TestModelAuth
  99. @pytest.fixture()
  100. def test_get_engine():
  101. """A default database engine.
  102. Returns:
  103. A default database engine.
  104. """
  105. enable_admin = True
  106. url = "sqlite:///test.db"
  107. return sqlmodel.create_engine(
  108. url,
  109. echo=False,
  110. connect_args={"check_same_thread": False} if enable_admin else {},
  111. )
  112. @pytest.fixture()
  113. def test_custom_auth_admin() -> Type[AuthProvider]:
  114. """A default auth provider.
  115. Returns:
  116. A default default auth provider.
  117. """
  118. class TestAuthProvider(AuthProvider):
  119. """A test auth provider."""
  120. login_path: str = "/login"
  121. logout_path: str = "/logout"
  122. def login(self):
  123. """Login."""
  124. pass
  125. def is_authenticated(self):
  126. """Is authenticated."""
  127. pass
  128. def get_admin_user(self):
  129. """Get admin user."""
  130. pass
  131. def logout(self):
  132. """Logout."""
  133. pass
  134. return TestAuthProvider
  135. def test_default_app(app: App):
  136. """Test creating an app with no args.
  137. Args:
  138. app: The app to test.
  139. """
  140. assert app.middleware == [HydrateMiddleware()]
  141. assert app.style == Style()
  142. assert app.admin_dash is None
  143. def test_multiple_states_error(monkeypatch, test_state, redundant_test_state):
  144. """Test that an error is thrown when multiple classes subclass rx.State.
  145. Args:
  146. monkeypatch: Pytest monkeypatch object.
  147. test_state: A test state subclassing rx.State.
  148. redundant_test_state: Another test state subclassing rx.State.
  149. """
  150. monkeypatch.delenv(constants.PYTEST_CURRENT_TEST)
  151. with pytest.raises(ValueError):
  152. App()
  153. def test_add_page_default_route(app: App, index_page, about_page):
  154. """Test adding a page to an app.
  155. Args:
  156. app: The app to test.
  157. index_page: The index page.
  158. about_page: The about page.
  159. """
  160. assert app.pages == {}
  161. app.add_page(index_page)
  162. assert set(app.pages.keys()) == {"index"}
  163. app.add_page(about_page)
  164. assert set(app.pages.keys()) == {"index", "about"}
  165. def test_add_page_set_route(app: App, index_page, windows_platform: bool):
  166. """Test adding a page to an app.
  167. Args:
  168. app: The app to test.
  169. index_page: The index page.
  170. windows_platform: Whether the system is windows.
  171. """
  172. route = "test" if windows_platform else "/test"
  173. assert app.pages == {}
  174. app.add_page(index_page, route=route)
  175. assert set(app.pages.keys()) == {"test"}
  176. def test_add_page_set_route_dynamic(index_page, windows_platform: bool):
  177. """Test adding a page with dynamic route variable to an app.
  178. Args:
  179. index_page: The index page.
  180. windows_platform: Whether the system is windows.
  181. """
  182. app = App(state=EmptyState)
  183. route = "/test/[dynamic]"
  184. if windows_platform:
  185. route.lstrip("/").replace("/", "\\")
  186. assert app.pages == {}
  187. app.add_page(index_page, route=route)
  188. assert set(app.pages.keys()) == {"test/[dynamic]"}
  189. assert "dynamic" in app.state.computed_vars
  190. assert app.state.computed_vars["dynamic"]._deps(objclass=EmptyState) == {
  191. constants.ROUTER
  192. }
  193. assert constants.ROUTER in app.state().computed_var_dependencies
  194. def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool):
  195. """Test adding a page to an app.
  196. Args:
  197. app: The app to test.
  198. index_page: The index page.
  199. windows_platform: Whether the system is windows.
  200. """
  201. route = "test\\nested" if windows_platform else "/test/nested"
  202. assert app.pages == {}
  203. app.add_page(index_page, route=route)
  204. assert set(app.pages.keys()) == {route.strip(os.path.sep)}
  205. def test_initialize_with_admin_dashboard(test_model):
  206. """Test setting the admin dashboard of an app.
  207. Args:
  208. test_model: The default model.
  209. """
  210. app = App(admin_dash=AdminDash(models=[test_model]))
  211. assert app.admin_dash is not None
  212. assert len(app.admin_dash.models) > 0
  213. assert app.admin_dash.models[0] == test_model
  214. def test_initialize_with_custom_admin_dashboard(
  215. test_get_engine,
  216. test_custom_auth_admin,
  217. test_model_auth,
  218. ):
  219. """Test setting the custom admin dashboard of an app.
  220. Args:
  221. test_get_engine: The default database engine.
  222. test_model_auth: The default model for an auth admin dashboard.
  223. test_custom_auth_admin: The custom auth provider.
  224. """
  225. custom_admin = Admin(engine=test_get_engine, auth_provider=test_custom_auth_admin)
  226. app = App(admin_dash=AdminDash(models=[test_model_auth], admin=custom_admin))
  227. assert app.admin_dash is not None
  228. assert app.admin_dash.admin is not None
  229. assert len(app.admin_dash.models) > 0
  230. assert app.admin_dash.models[0] == test_model_auth
  231. assert app.admin_dash.admin.auth_provider == test_custom_auth_admin
  232. def test_initialize_admin_dashboard_with_view_overrides(test_model):
  233. """Test setting the admin dashboard of an app with view class overridden.
  234. Args:
  235. test_model: The default model.
  236. """
  237. class TestModelView(ModelView):
  238. pass
  239. app = App(
  240. admin_dash=AdminDash(
  241. models=[test_model], view_overrides={test_model: TestModelView}
  242. )
  243. )
  244. assert app.admin_dash is not None
  245. assert app.admin_dash.models == [test_model]
  246. assert app.admin_dash.view_overrides[test_model] == TestModelView
  247. @pytest.mark.asyncio
  248. async def test_initialize_with_state(test_state: Type[ATestState], token: str):
  249. """Test setting the state of an app.
  250. Args:
  251. test_state: The default state.
  252. token: a Token.
  253. """
  254. app = App(state=test_state)
  255. assert app.state == test_state
  256. # Get a state for a given token.
  257. state = await app.state_manager.get_state(token)
  258. assert isinstance(state, test_state)
  259. assert state.var == 0 # type: ignore
  260. if isinstance(app.state_manager, StateManagerRedis):
  261. await app.state_manager.redis.close()
  262. @pytest.mark.asyncio
  263. async def test_set_and_get_state(test_state):
  264. """Test setting and getting the state of an app with different tokens.
  265. Args:
  266. test_state: The default state.
  267. """
  268. app = App(state=test_state)
  269. # Create two tokens.
  270. token1 = str(uuid.uuid4())
  271. token2 = str(uuid.uuid4())
  272. # Get the default state for each token.
  273. state1 = await app.state_manager.get_state(token1)
  274. state2 = await app.state_manager.get_state(token2)
  275. assert state1.var == 0 # type: ignore
  276. assert state2.var == 0 # type: ignore
  277. # Set the vars to different values.
  278. state1.var = 1
  279. state2.var = 2
  280. await app.state_manager.set_state(token1, state1)
  281. await app.state_manager.set_state(token2, state2)
  282. # Get the states again and check the values.
  283. state1 = await app.state_manager.get_state(token1)
  284. state2 = await app.state_manager.get_state(token2)
  285. assert state1.var == 1 # type: ignore
  286. assert state2.var == 2 # type: ignore
  287. if isinstance(app.state_manager, StateManagerRedis):
  288. await app.state_manager.redis.close()
  289. @pytest.mark.asyncio
  290. async def test_dynamic_var_event(test_state: Type[ATestState], token: str):
  291. """Test that the default handler of a dynamic generated var
  292. works as expected.
  293. Args:
  294. test_state: State Fixture.
  295. token: a Token.
  296. """
  297. state = test_state() # type: ignore
  298. state.add_var("int_val", int, 0)
  299. result = await state._process(
  300. Event(
  301. token=token,
  302. name=f"{test_state.get_name()}.set_int_val",
  303. router_data={"pathname": "/", "query": {}},
  304. payload={"value": 50},
  305. )
  306. ).__anext__()
  307. assert result.delta == {test_state.get_name(): {"int_val": 50}}
  308. @pytest.mark.asyncio
  309. @pytest.mark.parametrize(
  310. "event_tuples",
  311. [
  312. pytest.param(
  313. [
  314. (
  315. "list_mutation_test_state.make_friend",
  316. {
  317. "list_mutation_test_state": {
  318. "plain_friends": ["Tommy", "another-fd"]
  319. }
  320. },
  321. ),
  322. (
  323. "list_mutation_test_state.change_first_friend",
  324. {
  325. "list_mutation_test_state": {
  326. "plain_friends": ["Jenny", "another-fd"]
  327. }
  328. },
  329. ),
  330. ],
  331. id="append then __setitem__",
  332. ),
  333. pytest.param(
  334. [
  335. (
  336. "list_mutation_test_state.unfriend_first_friend",
  337. {"list_mutation_test_state": {"plain_friends": []}},
  338. ),
  339. (
  340. "list_mutation_test_state.make_friend",
  341. {"list_mutation_test_state": {"plain_friends": ["another-fd"]}},
  342. ),
  343. ],
  344. id="delitem then append",
  345. ),
  346. pytest.param(
  347. [
  348. (
  349. "list_mutation_test_state.make_friends_with_colleagues",
  350. {
  351. "list_mutation_test_state": {
  352. "plain_friends": ["Tommy", "Peter", "Jimmy"]
  353. }
  354. },
  355. ),
  356. (
  357. "list_mutation_test_state.remove_tommy",
  358. {"list_mutation_test_state": {"plain_friends": ["Peter", "Jimmy"]}},
  359. ),
  360. (
  361. "list_mutation_test_state.remove_last_friend",
  362. {"list_mutation_test_state": {"plain_friends": ["Peter"]}},
  363. ),
  364. (
  365. "list_mutation_test_state.unfriend_all_friends",
  366. {"list_mutation_test_state": {"plain_friends": []}},
  367. ),
  368. ],
  369. id="extend, remove, pop, clear",
  370. ),
  371. pytest.param(
  372. [
  373. (
  374. "list_mutation_test_state.add_jimmy_to_second_group",
  375. {
  376. "list_mutation_test_state": {
  377. "friends_in_nested_list": [["Tommy"], ["Jenny", "Jimmy"]]
  378. }
  379. },
  380. ),
  381. (
  382. "list_mutation_test_state.remove_first_person_from_first_group",
  383. {
  384. "list_mutation_test_state": {
  385. "friends_in_nested_list": [[], ["Jenny", "Jimmy"]]
  386. }
  387. },
  388. ),
  389. (
  390. "list_mutation_test_state.remove_first_group",
  391. {
  392. "list_mutation_test_state": {
  393. "friends_in_nested_list": [["Jenny", "Jimmy"]]
  394. }
  395. },
  396. ),
  397. ],
  398. id="nested list",
  399. ),
  400. pytest.param(
  401. [
  402. (
  403. "list_mutation_test_state.add_jimmy_to_tommy_friends",
  404. {
  405. "list_mutation_test_state": {
  406. "friends_in_dict": {"Tommy": ["Jenny", "Jimmy"]}
  407. }
  408. },
  409. ),
  410. (
  411. "list_mutation_test_state.remove_jenny_from_tommy",
  412. {
  413. "list_mutation_test_state": {
  414. "friends_in_dict": {"Tommy": ["Jimmy"]}
  415. }
  416. },
  417. ),
  418. (
  419. "list_mutation_test_state.tommy_has_no_fds",
  420. {"list_mutation_test_state": {"friends_in_dict": {"Tommy": []}}},
  421. ),
  422. ],
  423. id="list in dict",
  424. ),
  425. ],
  426. )
  427. async def test_list_mutation_detection__plain_list(
  428. event_tuples: List[Tuple[str, List[str]]],
  429. list_mutation_state: State,
  430. token: str,
  431. ):
  432. """Test list mutation detection
  433. when reassignment is not explicitly included in the logic.
  434. Args:
  435. event_tuples: From parametrization.
  436. list_mutation_state: A state with list mutation features.
  437. token: a Token.
  438. """
  439. for event_name, expected_delta in event_tuples:
  440. result = await list_mutation_state._process(
  441. Event(
  442. token=token,
  443. name=event_name,
  444. router_data={"pathname": "/", "query": {}},
  445. payload={},
  446. )
  447. ).__anext__()
  448. assert result.delta == expected_delta
  449. @pytest.mark.asyncio
  450. @pytest.mark.parametrize(
  451. "event_tuples",
  452. [
  453. pytest.param(
  454. [
  455. (
  456. "dict_mutation_test_state.add_age",
  457. {
  458. "dict_mutation_test_state": {
  459. "details": {"name": "Tommy", "age": 20}
  460. }
  461. },
  462. ),
  463. (
  464. "dict_mutation_test_state.change_name",
  465. {
  466. "dict_mutation_test_state": {
  467. "details": {"name": "Jenny", "age": 20}
  468. }
  469. },
  470. ),
  471. (
  472. "dict_mutation_test_state.remove_last_detail",
  473. {"dict_mutation_test_state": {"details": {"name": "Jenny"}}},
  474. ),
  475. ],
  476. id="update then __setitem__",
  477. ),
  478. pytest.param(
  479. [
  480. (
  481. "dict_mutation_test_state.clear_details",
  482. {"dict_mutation_test_state": {"details": {}}},
  483. ),
  484. (
  485. "dict_mutation_test_state.add_age",
  486. {"dict_mutation_test_state": {"details": {"age": 20}}},
  487. ),
  488. ],
  489. id="delitem then update",
  490. ),
  491. pytest.param(
  492. [
  493. (
  494. "dict_mutation_test_state.add_age",
  495. {
  496. "dict_mutation_test_state": {
  497. "details": {"name": "Tommy", "age": 20}
  498. }
  499. },
  500. ),
  501. (
  502. "dict_mutation_test_state.remove_name",
  503. {"dict_mutation_test_state": {"details": {"age": 20}}},
  504. ),
  505. (
  506. "dict_mutation_test_state.pop_out_age",
  507. {"dict_mutation_test_state": {"details": {}}},
  508. ),
  509. ],
  510. id="add, remove, pop",
  511. ),
  512. pytest.param(
  513. [
  514. (
  515. "dict_mutation_test_state.remove_home_address",
  516. {
  517. "dict_mutation_test_state": {
  518. "address": [{}, {"work": "work address"}]
  519. }
  520. },
  521. ),
  522. (
  523. "dict_mutation_test_state.add_street_to_home_address",
  524. {
  525. "dict_mutation_test_state": {
  526. "address": [
  527. {"street": "street address"},
  528. {"work": "work address"},
  529. ]
  530. }
  531. },
  532. ),
  533. ],
  534. id="dict in list",
  535. ),
  536. pytest.param(
  537. [
  538. (
  539. "dict_mutation_test_state.change_friend_name",
  540. {
  541. "dict_mutation_test_state": {
  542. "friend_in_nested_dict": {
  543. "name": "Nikhil",
  544. "friend": {"name": "Tommy"},
  545. }
  546. }
  547. },
  548. ),
  549. (
  550. "dict_mutation_test_state.add_friend_age",
  551. {
  552. "dict_mutation_test_state": {
  553. "friend_in_nested_dict": {
  554. "name": "Nikhil",
  555. "friend": {"name": "Tommy", "age": 30},
  556. }
  557. }
  558. },
  559. ),
  560. (
  561. "dict_mutation_test_state.remove_friend",
  562. {
  563. "dict_mutation_test_state": {
  564. "friend_in_nested_dict": {"name": "Nikhil"}
  565. }
  566. },
  567. ),
  568. ],
  569. id="nested dict",
  570. ),
  571. ],
  572. )
  573. async def test_dict_mutation_detection__plain_list(
  574. event_tuples: List[Tuple[str, List[str]]],
  575. dict_mutation_state: State,
  576. token: str,
  577. ):
  578. """Test dict mutation detection
  579. when reassignment is not explicitly included in the logic.
  580. Args:
  581. event_tuples: From parametrization.
  582. dict_mutation_state: A state with dict mutation features.
  583. token: a Token.
  584. """
  585. for event_name, expected_delta in event_tuples:
  586. result = await dict_mutation_state._process(
  587. Event(
  588. token=token,
  589. name=event_name,
  590. router_data={"pathname": "/", "query": {}},
  591. payload={},
  592. )
  593. ).__anext__()
  594. assert result.delta == expected_delta
  595. @pytest.mark.asyncio
  596. @pytest.mark.parametrize(
  597. ("state", "delta"),
  598. [
  599. (
  600. FileUploadState,
  601. {"file_upload_state": {"img_list": ["image1.jpg", "image2.jpg"]}},
  602. ),
  603. (
  604. ChildFileUploadState,
  605. {
  606. "file_state_base1.child_file_upload_state": {
  607. "img_list": ["image1.jpg", "image2.jpg"]
  608. }
  609. },
  610. ),
  611. (
  612. GrandChildFileUploadState,
  613. {
  614. "file_state_base1.file_state_base2.grand_child_file_upload_state": {
  615. "img_list": ["image1.jpg", "image2.jpg"]
  616. }
  617. },
  618. ),
  619. ],
  620. )
  621. async def test_upload_file(tmp_path, state, delta, token: str):
  622. """Test that file upload works correctly.
  623. Args:
  624. tmp_path: Temporary path.
  625. state: The state class.
  626. delta: Expected delta
  627. token: a Token.
  628. """
  629. state._tmp_path = tmp_path
  630. # The App state must be the "root" of the state tree
  631. app = App(state=state if state is FileUploadState else FileStateBase1)
  632. app.event_namespace.emit = AsyncMock() # type: ignore
  633. current_state = await app.state_manager.get_state(token)
  634. data = b"This is binary data"
  635. # Create a binary IO object and write data to it
  636. bio = io.BytesIO()
  637. bio.write(data)
  638. state_name = state.get_full_name().partition(".")[2] or state.get_name()
  639. handler_prefix = f"{token}:{state_name}"
  640. file1 = UploadFile(
  641. filename=f"{handler_prefix}.multi_handle_upload:True:image1.jpg",
  642. file=bio,
  643. )
  644. file2 = UploadFile(
  645. filename=f"{handler_prefix}.multi_handle_upload:True:image2.jpg",
  646. file=bio,
  647. )
  648. upload_fn = upload(app)
  649. await upload_fn([file1, file2])
  650. state_update = StateUpdate(delta=delta, events=[], final=True)
  651. app.event_namespace.emit.assert_called_with( # type: ignore
  652. "event", state_update.json(), to=current_state.router.session.session_id
  653. )
  654. current_state = await app.state_manager.get_state(token)
  655. state_dict = current_state.dict()
  656. for substate in state.get_full_name().split(".")[1:]:
  657. state_dict = state_dict[substate]
  658. assert state_dict["img_list"] == [
  659. "image1.jpg",
  660. "image2.jpg",
  661. ]
  662. if isinstance(app.state_manager, StateManagerRedis):
  663. await app.state_manager.redis.close()
  664. @pytest.mark.asyncio
  665. @pytest.mark.parametrize(
  666. "state",
  667. [FileUploadState, ChildFileUploadState, GrandChildFileUploadState],
  668. )
  669. async def test_upload_file_without_annotation(state, tmp_path, token):
  670. """Test that an error is thrown when there's no param annotated with rx.UploadFile or List[UploadFile].
  671. Args:
  672. state: The state class.
  673. tmp_path: Temporary path.
  674. token: a Token.
  675. """
  676. data = b"This is binary data"
  677. # Create a binary IO object and write data to it
  678. bio = io.BytesIO()
  679. bio.write(data)
  680. state._tmp_path = tmp_path
  681. # The App state must be the "root" of the state tree
  682. app = App(state=state if state is FileUploadState else FileStateBase1)
  683. state_name = state.get_full_name().partition(".")[2] or state.get_name()
  684. handler_prefix = f"{token}:{state_name}"
  685. file1 = UploadFile(
  686. filename=f"{handler_prefix}.handle_upload2:True:image1.jpg",
  687. file=bio,
  688. )
  689. file2 = UploadFile(
  690. filename=f"{handler_prefix}.handle_upload2:True:image2.jpg",
  691. file=bio,
  692. )
  693. fn = upload(app)
  694. with pytest.raises(ValueError) as err:
  695. await fn([file1, file2])
  696. assert (
  697. err.value.args[0]
  698. == f"`{state_name}.handle_upload2` handler should have a parameter annotated as List[rx.UploadFile]"
  699. )
  700. if isinstance(app.state_manager, StateManagerRedis):
  701. await app.state_manager.redis.close()
  702. class DynamicState(State):
  703. """State class for testing dynamic route var.
  704. This is defined at module level because event handlers cannot be addressed
  705. correctly when the class is defined as a local.
  706. There are several counters:
  707. * loaded: counts how many times `on_load` was triggered by the hydrate middleware
  708. * counter: counts how many times `on_counter` was triggered by a non-navigational event
  709. -> these events should NOT trigger reload or recalculation of router_data dependent vars
  710. * side_effect_counter: counts how many times a computed var was
  711. recalculated when the dynamic route var was dirty
  712. """
  713. loaded: int = 0
  714. counter: int = 0
  715. # side_effect_counter: int = 0
  716. def on_load(self):
  717. """Event handler for page on_load, should trigger for all navigation events."""
  718. self.loaded = self.loaded + 1
  719. def on_counter(self):
  720. """Increment the counter var."""
  721. self.counter = self.counter + 1
  722. @ComputedVar
  723. def comp_dynamic(self) -> str:
  724. """A computed var that depends on the dynamic var.
  725. Returns:
  726. same as self.dynamic
  727. """
  728. # self.side_effect_counter = self.side_effect_counter + 1
  729. return self.dynamic
  730. @pytest.mark.asyncio
  731. async def test_dynamic_route_var_route_change_completed_on_load(
  732. index_page,
  733. windows_platform: bool,
  734. token: str,
  735. ):
  736. """Create app with dynamic route var, and simulate navigation.
  737. on_load should fire, allowing any additional vars to be updated before the
  738. initial page hydrate.
  739. Args:
  740. index_page: The index page.
  741. windows_platform: Whether the system is windows.
  742. token: a Token.
  743. """
  744. arg_name = "dynamic"
  745. route = f"/test/[{arg_name}]"
  746. if windows_platform:
  747. route.lstrip("/").replace("/", "\\")
  748. app = App(state=DynamicState)
  749. assert arg_name not in app.state.vars
  750. app.add_page(index_page, route=route, on_load=DynamicState.on_load) # type: ignore
  751. assert arg_name in app.state.vars
  752. assert arg_name in app.state.computed_vars
  753. assert app.state.computed_vars[arg_name]._deps(objclass=DynamicState) == {
  754. constants.ROUTER
  755. }
  756. assert constants.ROUTER in app.state().computed_var_dependencies
  757. sid = "mock_sid"
  758. client_ip = "127.0.0.1"
  759. state = await app.state_manager.get_state(token)
  760. assert state.dynamic == ""
  761. exp_vals = ["foo", "foobar", "baz"]
  762. def _event(name, val, **kwargs):
  763. return Event(
  764. token=kwargs.pop("token", token),
  765. name=name,
  766. router_data=kwargs.pop(
  767. "router_data", {"pathname": route, "query": {arg_name: val}}
  768. ),
  769. payload=kwargs.pop("payload", {}),
  770. **kwargs,
  771. )
  772. def _dynamic_state_event(name, val, **kwargs):
  773. return _event(
  774. name=format.format_event_handler(getattr(DynamicState, name)), # type: ignore
  775. val=val,
  776. **kwargs,
  777. )
  778. prev_exp_val = ""
  779. for exp_index, exp_val in enumerate(exp_vals):
  780. hydrate_event = _event(name=get_hydrate_event(state), val=exp_val)
  781. exp_router_data = {
  782. "headers": {},
  783. "ip": client_ip,
  784. "sid": sid,
  785. "token": token,
  786. **hydrate_event.router_data,
  787. }
  788. exp_router = RouterData(exp_router_data)
  789. process_coro = process(
  790. app,
  791. event=hydrate_event,
  792. sid=sid,
  793. headers={},
  794. client_ip=client_ip,
  795. )
  796. update = await process_coro.__anext__() # type: ignore
  797. # route change triggers: [full state dict, call on_load events, call set_is_hydrated(True)]
  798. assert update == StateUpdate(
  799. delta={
  800. state.get_name(): {
  801. arg_name: exp_val,
  802. f"comp_{arg_name}": exp_val,
  803. constants.CompileVars.IS_HYDRATED: False,
  804. "loaded": exp_index,
  805. "counter": exp_index,
  806. "router": exp_router,
  807. # "side_effect_counter": exp_index,
  808. }
  809. },
  810. events=[
  811. _dynamic_state_event(
  812. name="on_load",
  813. val=exp_val,
  814. router_data=exp_router_data,
  815. ),
  816. _dynamic_state_event(
  817. name="set_is_hydrated",
  818. payload={"value": True},
  819. val=exp_val,
  820. router_data=exp_router_data,
  821. ),
  822. ],
  823. )
  824. if isinstance(app.state_manager, StateManagerRedis):
  825. # When redis is used, the state is not updated until the processing is complete
  826. state = await app.state_manager.get_state(token)
  827. assert state.dynamic == prev_exp_val
  828. # complete the processing
  829. with pytest.raises(StopAsyncIteration):
  830. await process_coro.__anext__() # type: ignore
  831. # check that router data was written to the state_manager store
  832. state = await app.state_manager.get_state(token)
  833. assert state.dynamic == exp_val
  834. process_coro = process(
  835. app,
  836. event=_dynamic_state_event(name="on_load", val=exp_val),
  837. sid=sid,
  838. headers={},
  839. client_ip=client_ip,
  840. )
  841. on_load_update = await process_coro.__anext__() # type: ignore
  842. assert on_load_update == StateUpdate(
  843. delta={
  844. state.get_name(): {
  845. # These computed vars _shouldn't_ be here, because they didn't change
  846. arg_name: exp_val,
  847. f"comp_{arg_name}": exp_val,
  848. "loaded": exp_index + 1,
  849. },
  850. },
  851. events=[],
  852. )
  853. # complete the processing
  854. with pytest.raises(StopAsyncIteration):
  855. await process_coro.__anext__() # type: ignore
  856. process_coro = process(
  857. app,
  858. event=_dynamic_state_event(
  859. name="set_is_hydrated", payload={"value": True}, val=exp_val
  860. ),
  861. sid=sid,
  862. headers={},
  863. client_ip=client_ip,
  864. )
  865. on_set_is_hydrated_update = await process_coro.__anext__() # type: ignore
  866. assert on_set_is_hydrated_update == StateUpdate(
  867. delta={
  868. state.get_name(): {
  869. # These computed vars _shouldn't_ be here, because they didn't change
  870. arg_name: exp_val,
  871. f"comp_{arg_name}": exp_val,
  872. "is_hydrated": True,
  873. },
  874. },
  875. events=[],
  876. )
  877. # complete the processing
  878. with pytest.raises(StopAsyncIteration):
  879. await process_coro.__anext__() # type: ignore
  880. # a simple state update event should NOT trigger on_load or route var side effects
  881. process_coro = process(
  882. app,
  883. event=_dynamic_state_event(name="on_counter", val=exp_val),
  884. sid=sid,
  885. headers={},
  886. client_ip=client_ip,
  887. )
  888. update = await process_coro.__anext__() # type: ignore
  889. assert update == StateUpdate(
  890. delta={
  891. state.get_name(): {
  892. # These computed vars _shouldn't_ be here, because they didn't change
  893. f"comp_{arg_name}": exp_val,
  894. arg_name: exp_val,
  895. "counter": exp_index + 1,
  896. }
  897. },
  898. events=[],
  899. )
  900. # complete the processing
  901. with pytest.raises(StopAsyncIteration):
  902. await process_coro.__anext__() # type: ignore
  903. prev_exp_val = exp_val
  904. state = await app.state_manager.get_state(token)
  905. assert state.loaded == len(exp_vals)
  906. assert state.counter == len(exp_vals)
  907. # print(f"Expected {exp_vals} rendering side effects, got {state.side_effect_counter}")
  908. # assert state.side_effect_counter == len(exp_vals)
  909. if isinstance(app.state_manager, StateManagerRedis):
  910. await app.state_manager.redis.close()
  911. @pytest.mark.asyncio
  912. async def test_process_events(mocker, token: str):
  913. """Test that an event is processed properly and that it is postprocessed
  914. n+1 times. Also check that the processing flag of the last stateupdate is set to
  915. False.
  916. Args:
  917. mocker: mocker object.
  918. token: a Token.
  919. """
  920. router_data = {
  921. "pathname": "/",
  922. "query": {},
  923. "token": token,
  924. "sid": "mock_sid",
  925. "headers": {},
  926. "ip": "127.0.0.1",
  927. }
  928. app = App(state=GenState)
  929. mocker.patch.object(app, "postprocess", AsyncMock())
  930. event = Event(
  931. token=token, name="gen_state.go", payload={"c": 5}, router_data=router_data
  932. )
  933. async for _update in process(app, event, "mock_sid", {}, "127.0.0.1"): # type: ignore
  934. pass
  935. assert (await app.state_manager.get_state(token)).value == 5
  936. assert app.postprocess.call_count == 6
  937. if isinstance(app.state_manager, StateManagerRedis):
  938. await app.state_manager.redis.close()
  939. @pytest.mark.parametrize(
  940. ("state", "overlay_component", "exp_page_child"),
  941. [
  942. (None, default_overlay_component, None),
  943. (None, None, None),
  944. (None, Text.create("foo"), Text),
  945. (State, default_overlay_component, Fragment),
  946. (State, None, None),
  947. (State, Text.create("foo"), Text),
  948. (State, lambda: Text.create("foo"), Text),
  949. ],
  950. )
  951. def test_overlay_component(
  952. state: State | None,
  953. overlay_component: Component | ComponentCallable | None,
  954. exp_page_child: Type[Component] | None,
  955. ):
  956. """Test that the overlay component is set correctly.
  957. Args:
  958. state: The state class to pass to App.
  959. overlay_component: The overlay_component to pass to App.
  960. exp_page_child: The type of the expected child in the page fragment.
  961. """
  962. app = App(state=state, overlay_component=overlay_component)
  963. if exp_page_child is None:
  964. assert app.overlay_component is None
  965. elif isinstance(exp_page_child, Fragment):
  966. assert app.overlay_component is not None
  967. generated_component = app._generate_component(app.overlay_component) # type: ignore
  968. assert isinstance(generated_component, Fragment)
  969. assert isinstance(
  970. generated_component.children[0],
  971. Cond, # ConnectionModal is a Cond under the hood
  972. )
  973. else:
  974. assert app.overlay_component is not None
  975. assert isinstance(
  976. app._generate_component(app.overlay_component), # type: ignore
  977. exp_page_child,
  978. )
  979. app.add_page(Box.create("Index"), route="/test")
  980. page = app.pages["test"]
  981. if exp_page_child is not None:
  982. assert len(page.children) == 3
  983. children_types = (type(child) for child in page.children)
  984. assert exp_page_child in children_types
  985. else:
  986. assert len(page.children) == 2
  987. @pytest.fixture
  988. def compilable_app(tmp_path) -> Generator[tuple[App, Path], None, None]:
  989. """Fixture for an app that can be compiled.
  990. Args:
  991. tmp_path: Temporary path.
  992. Yields:
  993. Tuple containing (app instance, Path to ".web" directory)
  994. The working directory is set to the app dir (parent of .web),
  995. allowing app.compile() to be called.
  996. """
  997. app_path = tmp_path / "app"
  998. web_dir = app_path / ".web"
  999. web_dir.mkdir(parents=True)
  1000. (web_dir / "package.json").touch()
  1001. app = App()
  1002. app.get_frontend_packages = unittest.mock.Mock()
  1003. with chdir(app_path):
  1004. yield app, web_dir
  1005. def test_app_wrap_compile_theme(compilable_app):
  1006. """Test that the radix theme component wraps the app.
  1007. Args:
  1008. compilable_app: compilable_app fixture.
  1009. """
  1010. app, web_dir = compilable_app
  1011. app.theme = rdxt.theme(accent_color="plum")
  1012. app.compile()
  1013. app_js_contents = (web_dir / "pages" / "_app.js").read_text()
  1014. app_js_lines = [
  1015. line.strip() for line in app_js_contents.splitlines() if line.strip()
  1016. ]
  1017. assert (
  1018. "function AppWrap({children}) {"
  1019. "return ("
  1020. "<RadixThemesTheme accentColor={`plum`}>"
  1021. "{children}"
  1022. "</RadixThemesTheme>"
  1023. ")"
  1024. "}"
  1025. ) in "".join(app_js_lines)
  1026. def test_app_wrap_priority(compilable_app):
  1027. """Test that the app wrap components are wrapped in the correct order.
  1028. Args:
  1029. compilable_app: compilable_app fixture.
  1030. """
  1031. app, web_dir = compilable_app
  1032. class Fragment1(Component):
  1033. tag = "Fragment1"
  1034. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  1035. return {(99, "Box"): Box.create()}
  1036. class Fragment2(Component):
  1037. tag = "Fragment2"
  1038. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  1039. return {(50, "Text"): Text.create()}
  1040. class Fragment3(Component):
  1041. tag = "Fragment3"
  1042. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]:
  1043. return {(10, "Fragment2"): Fragment2.create()}
  1044. def page():
  1045. return Fragment1.create(Fragment3.create())
  1046. app.add_page(page)
  1047. app.compile()
  1048. app_js_contents = (web_dir / "pages" / "_app.js").read_text()
  1049. app_js_lines = [
  1050. line.strip() for line in app_js_contents.splitlines() if line.strip()
  1051. ]
  1052. assert (
  1053. "function AppWrap({children}) {"
  1054. "return ("
  1055. "<Box>"
  1056. "<ChakraProvider theme={extendTheme(theme)}>"
  1057. "<Global styles={GlobalStyles}/>"
  1058. "<ChakraColorModeProvider>"
  1059. "<Text>"
  1060. "<Fragment2>"
  1061. "{children}"
  1062. "</Fragment2>"
  1063. "</Text>"
  1064. "</ChakraColorModeProvider>"
  1065. "</ChakraProvider>"
  1066. "</Box>"
  1067. ")"
  1068. "}"
  1069. ) in "".join(app_js_lines)