test_app.py 39 KB

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