test_app.py 52 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810
  1. from __future__ import annotations
  2. import functools
  3. import io
  4. import json
  5. import os.path
  6. import re
  7. import unittest.mock
  8. import uuid
  9. from collections.abc import Generator
  10. from contextlib import nullcontext as does_not_raise
  11. from pathlib import Path
  12. from unittest.mock import AsyncMock
  13. import pytest
  14. import sqlmodel
  15. from fastapi import FastAPI, UploadFile
  16. from pytest_mock import MockerFixture
  17. from starlette_admin.auth import AuthProvider
  18. from starlette_admin.contrib.sqla.admin import Admin
  19. from starlette_admin.contrib.sqla.view import ModelView
  20. import reflex as rx
  21. from reflex import AdminDash, constants
  22. from reflex.app import (
  23. App,
  24. ComponentCallable,
  25. OverlayFragment,
  26. default_overlay_component,
  27. process,
  28. upload,
  29. )
  30. from reflex.components import Component
  31. from reflex.components.base.bare import Bare
  32. from reflex.components.base.fragment import Fragment
  33. from reflex.components.core.cond import Cond
  34. from reflex.components.radix.themes.typography.text import Text
  35. from reflex.event import Event
  36. from reflex.middleware import HydrateMiddleware
  37. from reflex.model import Model
  38. from reflex.state import (
  39. BaseState,
  40. OnLoadInternalState,
  41. RouterData,
  42. State,
  43. StateManagerDisk,
  44. StateManagerMemory,
  45. StateManagerRedis,
  46. StateUpdate,
  47. _substate_key,
  48. )
  49. from reflex.style import Style
  50. from reflex.utils import console, exceptions, format
  51. from reflex.vars.base import computed_var
  52. from .conftest import chdir
  53. from .states import (
  54. ChildFileUploadState,
  55. FileStateBase1,
  56. FileUploadState,
  57. GenState,
  58. GrandChildFileUploadState,
  59. )
  60. class EmptyState(BaseState):
  61. """An empty state."""
  62. pass
  63. @pytest.fixture
  64. def index_page() -> ComponentCallable:
  65. """An index page.
  66. Returns:
  67. The index page.
  68. """
  69. def index():
  70. return rx.box("Index")
  71. return index
  72. @pytest.fixture
  73. def about_page() -> ComponentCallable:
  74. """An about page.
  75. Returns:
  76. The about page.
  77. """
  78. def about():
  79. return rx.box("About")
  80. return about
  81. class ATestState(BaseState):
  82. """A simple state for testing."""
  83. var: int
  84. @pytest.fixture()
  85. def test_state() -> type[BaseState]:
  86. """A default state.
  87. Returns:
  88. A default state.
  89. """
  90. return ATestState
  91. @pytest.fixture()
  92. def redundant_test_state() -> type[BaseState]:
  93. """A default state.
  94. Returns:
  95. A default state.
  96. """
  97. class RedundantTestState(BaseState):
  98. var: int
  99. return RedundantTestState
  100. @pytest.fixture(scope="session")
  101. def test_model() -> type[Model]:
  102. """A default model.
  103. Returns:
  104. A default model.
  105. """
  106. class TestModel(Model, table=True):
  107. pass
  108. return TestModel
  109. @pytest.fixture(scope="session")
  110. def test_model_auth() -> type[Model]:
  111. """A default model.
  112. Returns:
  113. A default model.
  114. """
  115. class TestModelAuth(Model, table=True):
  116. """A test model with auth."""
  117. pass
  118. return TestModelAuth
  119. @pytest.fixture()
  120. def test_get_engine():
  121. """A default database engine.
  122. Returns:
  123. A default database engine.
  124. """
  125. enable_admin = True
  126. url = "sqlite:///test.db"
  127. return sqlmodel.create_engine(
  128. url,
  129. echo=False,
  130. connect_args={"check_same_thread": False} if enable_admin else {},
  131. )
  132. @pytest.fixture()
  133. def test_custom_auth_admin() -> type[AuthProvider]:
  134. """A default auth provider.
  135. Returns:
  136. A default default auth provider.
  137. """
  138. class TestAuthProvider(AuthProvider):
  139. """A test auth provider."""
  140. login_path: str = "/login"
  141. logout_path: str = "/logout"
  142. def login(self): # pyright: ignore [reportIncompatibleMethodOverride]
  143. """Login."""
  144. pass
  145. def is_authenticated(self): # pyright: ignore [reportIncompatibleMethodOverride]
  146. """Is authenticated."""
  147. pass
  148. def get_admin_user(self): # pyright: ignore [reportIncompatibleMethodOverride]
  149. """Get admin user."""
  150. pass
  151. def logout(self): # pyright: ignore [reportIncompatibleMethodOverride]
  152. """Logout."""
  153. pass
  154. return TestAuthProvider
  155. def test_default_app(app: App):
  156. """Test creating an app with no args.
  157. Args:
  158. app: The app to test.
  159. """
  160. assert app._middlewares == [HydrateMiddleware()]
  161. assert app.style == Style()
  162. assert app.admin_dash is None
  163. def test_multiple_states_error(monkeypatch, test_state, redundant_test_state):
  164. """Test that an error is thrown when multiple classes subclass rx.BaseState.
  165. Args:
  166. monkeypatch: Pytest monkeypatch object.
  167. test_state: A test state subclassing rx.BaseState.
  168. redundant_test_state: Another test state subclassing rx.BaseState.
  169. """
  170. monkeypatch.delenv(constants.PYTEST_CURRENT_TEST)
  171. with pytest.raises(ValueError):
  172. App()
  173. def test_add_page_default_route(app: App, index_page, about_page):
  174. """Test adding a page to an app.
  175. Args:
  176. app: The app to test.
  177. index_page: The index page.
  178. about_page: The about page.
  179. """
  180. assert app._pages == {}
  181. assert app._unevaluated_pages == {}
  182. app.add_page(index_page)
  183. app._compile_page("index")
  184. assert app._pages.keys() == {"index"}
  185. app.add_page(about_page)
  186. app._compile_page("about")
  187. assert app._pages.keys() == {"index", "about"}
  188. def test_add_page_set_route(app: App, index_page, windows_platform: bool):
  189. """Test adding a page to an app.
  190. Args:
  191. app: The app to test.
  192. index_page: The index page.
  193. windows_platform: Whether the system is windows.
  194. """
  195. route = "test" if windows_platform else "/test"
  196. assert app._unevaluated_pages == {}
  197. app.add_page(index_page, route=route)
  198. app._compile_page("test")
  199. assert app._pages.keys() == {"test"}
  200. def test_add_page_set_route_dynamic(index_page, windows_platform: bool):
  201. """Test adding a page with dynamic route variable to an app.
  202. Args:
  203. index_page: The index page.
  204. windows_platform: Whether the system is windows.
  205. """
  206. app = App(_state=EmptyState)
  207. assert app._state is not None
  208. route = "/test/[dynamic]"
  209. assert app._unevaluated_pages == {}
  210. app.add_page(index_page, route=route)
  211. app._compile_page("test/[dynamic]")
  212. assert app._pages.keys() == {"test/[dynamic]"}
  213. assert "dynamic" in app._state.computed_vars
  214. assert app._state.computed_vars["dynamic"]._deps(objclass=EmptyState) == {
  215. EmptyState.get_full_name(): {constants.ROUTER},
  216. }
  217. assert constants.ROUTER in app._state()._var_dependencies
  218. def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool):
  219. """Test adding a page to an app.
  220. Args:
  221. app: The app to test.
  222. index_page: The index page.
  223. windows_platform: Whether the system is windows.
  224. """
  225. route = "test\\nested" if windows_platform else "/test/nested"
  226. assert app._unevaluated_pages == {}
  227. app.add_page(index_page, route=route)
  228. assert app._unevaluated_pages.keys() == {route.strip(os.path.sep)}
  229. def test_add_page_invalid_api_route(app: App, index_page):
  230. """Test adding a page with an invalid route to an app.
  231. Args:
  232. app: The app to test.
  233. index_page: The index page.
  234. """
  235. with pytest.raises(ValueError):
  236. app.add_page(index_page, route="api")
  237. with pytest.raises(ValueError):
  238. app.add_page(index_page, route="/api")
  239. with pytest.raises(ValueError):
  240. app.add_page(index_page, route="/api/")
  241. with pytest.raises(ValueError):
  242. app.add_page(index_page, route="api/foo")
  243. with pytest.raises(ValueError):
  244. app.add_page(index_page, route="/api/foo")
  245. # These should be fine
  246. app.add_page(index_page, route="api2")
  247. app.add_page(index_page, route="/foo/api")
  248. def page1():
  249. return rx.fragment()
  250. def page2():
  251. return rx.fragment()
  252. def index():
  253. return rx.fragment()
  254. @pytest.mark.parametrize(
  255. ("first_page", "second_page", "route"),
  256. [
  257. (index, index, None),
  258. (page1, page1, None),
  259. ],
  260. )
  261. def test_add_the_same_page(
  262. mocker: MockerFixture, app: App, first_page, second_page, route
  263. ):
  264. app.add_page(first_page, route=route)
  265. mock_object = mocker.Mock()
  266. mocker.patch.object(
  267. console,
  268. "warn",
  269. mock_object,
  270. )
  271. app.add_page(second_page, route="/" + route.strip("/") if route else None)
  272. assert mock_object.call_count == 1
  273. @pytest.mark.parametrize(
  274. ("first_page", "second_page", "route"),
  275. [
  276. (lambda: rx.fragment(), lambda: rx.fragment(rx.text("second")), "/"),
  277. (rx.fragment(rx.text("first")), rx.fragment(rx.text("second")), "/page1"),
  278. (
  279. lambda: rx.fragment(rx.text("first")),
  280. rx.fragment(rx.text("second")),
  281. "page3",
  282. ),
  283. (page1, page2, "page1"),
  284. ],
  285. )
  286. def test_add_duplicate_page_route_error(app: App, first_page, second_page, route):
  287. app.add_page(first_page, route=route)
  288. with pytest.raises(ValueError):
  289. app.add_page(second_page, route="/" + route.strip("/") if route else None)
  290. def test_initialize_with_admin_dashboard(test_model):
  291. """Test setting the admin dashboard of an app.
  292. Args:
  293. test_model: The default model.
  294. """
  295. app = App(admin_dash=AdminDash(models=[test_model]))
  296. assert app.admin_dash is not None
  297. assert len(app.admin_dash.models) > 0
  298. assert app.admin_dash.models[0] == test_model
  299. def test_initialize_with_custom_admin_dashboard(
  300. test_get_engine,
  301. test_custom_auth_admin,
  302. test_model_auth,
  303. ):
  304. """Test setting the custom admin dashboard of an app.
  305. Args:
  306. test_get_engine: The default database engine.
  307. test_model_auth: The default model for an auth admin dashboard.
  308. test_custom_auth_admin: The custom auth provider.
  309. """
  310. custom_auth_provider = test_custom_auth_admin()
  311. custom_admin = Admin(engine=test_get_engine, auth_provider=custom_auth_provider)
  312. app = App(admin_dash=AdminDash(models=[test_model_auth], admin=custom_admin))
  313. assert app.admin_dash is not None
  314. assert app.admin_dash.admin is not None
  315. assert len(app.admin_dash.models) > 0
  316. assert app.admin_dash.models[0] == test_model_auth
  317. assert app.admin_dash.admin.auth_provider == custom_auth_provider
  318. def test_initialize_admin_dashboard_with_view_overrides(test_model):
  319. """Test setting the admin dashboard of an app with view class overridden.
  320. Args:
  321. test_model: The default model.
  322. """
  323. class TestModelView(ModelView):
  324. pass
  325. app = App(
  326. admin_dash=AdminDash(
  327. models=[test_model], view_overrides={test_model: TestModelView}
  328. )
  329. )
  330. assert app.admin_dash is not None
  331. assert app.admin_dash.models == [test_model]
  332. assert app.admin_dash.view_overrides[test_model] == TestModelView
  333. @pytest.mark.asyncio
  334. async def test_initialize_with_state(test_state: type[ATestState], token: str):
  335. """Test setting the state of an app.
  336. Args:
  337. test_state: The default state.
  338. token: a Token.
  339. """
  340. app = App(_state=test_state)
  341. assert app._state == test_state
  342. # Get a state for a given token.
  343. state = await app.state_manager.get_state(_substate_key(token, test_state))
  344. assert isinstance(state, test_state)
  345. assert state.var == 0
  346. if isinstance(app.state_manager, StateManagerRedis):
  347. await app.state_manager.close()
  348. @pytest.mark.asyncio
  349. async def test_set_and_get_state(test_state):
  350. """Test setting and getting the state of an app with different tokens.
  351. Args:
  352. test_state: The default state.
  353. """
  354. app = App(_state=test_state)
  355. # Create two tokens.
  356. token1 = str(uuid.uuid4()) + f"_{test_state.get_full_name()}"
  357. token2 = str(uuid.uuid4()) + f"_{test_state.get_full_name()}"
  358. # Get the default state for each token.
  359. state1 = await app.state_manager.get_state(token1)
  360. state2 = await app.state_manager.get_state(token2)
  361. assert state1.var == 0
  362. assert state2.var == 0
  363. # Set the vars to different values.
  364. state1.var = 1
  365. state2.var = 2
  366. await app.state_manager.set_state(token1, state1)
  367. await app.state_manager.set_state(token2, state2)
  368. # Get the states again and check the values.
  369. state1 = await app.state_manager.get_state(token1)
  370. state2 = await app.state_manager.get_state(token2)
  371. assert state1.var == 1
  372. assert state2.var == 2
  373. if isinstance(app.state_manager, StateManagerRedis):
  374. await app.state_manager.close()
  375. @pytest.mark.asyncio
  376. async def test_dynamic_var_event(test_state: type[ATestState], token: str):
  377. """Test that the default handler of a dynamic generated var
  378. works as expected.
  379. Args:
  380. test_state: State Fixture.
  381. token: a Token.
  382. """
  383. state = test_state() # pyright: ignore [reportCallIssue]
  384. state.add_var("int_val", int, 0)
  385. async for result in state._process(
  386. Event(
  387. token=token,
  388. name=f"{test_state.get_name()}.set_int_val",
  389. router_data={"pathname": "/", "query": {}},
  390. payload={"value": 50},
  391. )
  392. ):
  393. assert result.delta == {test_state.get_name(): {"int_val": 50}}
  394. @pytest.mark.asyncio
  395. @pytest.mark.parametrize(
  396. "event_tuples",
  397. [
  398. pytest.param(
  399. [
  400. (
  401. "make_friend",
  402. {"plain_friends": ["Tommy", "another-fd"]},
  403. ),
  404. (
  405. "change_first_friend",
  406. {"plain_friends": ["Jenny", "another-fd"]},
  407. ),
  408. ],
  409. id="append then __setitem__",
  410. ),
  411. pytest.param(
  412. [
  413. (
  414. "unfriend_first_friend",
  415. {"plain_friends": []},
  416. ),
  417. (
  418. "make_friend",
  419. {"plain_friends": ["another-fd"]},
  420. ),
  421. ],
  422. id="delitem then append",
  423. ),
  424. pytest.param(
  425. [
  426. (
  427. "make_friends_with_colleagues",
  428. {"plain_friends": ["Tommy", "Peter", "Jimmy"]},
  429. ),
  430. (
  431. "remove_tommy",
  432. {"plain_friends": ["Peter", "Jimmy"]},
  433. ),
  434. (
  435. "remove_last_friend",
  436. {"plain_friends": ["Peter"]},
  437. ),
  438. (
  439. "unfriend_all_friends",
  440. {"plain_friends": []},
  441. ),
  442. ],
  443. id="extend, remove, pop, clear",
  444. ),
  445. pytest.param(
  446. [
  447. (
  448. "add_jimmy_to_second_group",
  449. {"friends_in_nested_list": [["Tommy"], ["Jenny", "Jimmy"]]},
  450. ),
  451. (
  452. "remove_first_person_from_first_group",
  453. {"friends_in_nested_list": [[], ["Jenny", "Jimmy"]]},
  454. ),
  455. (
  456. "remove_first_group",
  457. {"friends_in_nested_list": [["Jenny", "Jimmy"]]},
  458. ),
  459. ],
  460. id="nested list",
  461. ),
  462. pytest.param(
  463. [
  464. (
  465. "add_jimmy_to_tommy_friends",
  466. {"friends_in_dict": {"Tommy": ["Jenny", "Jimmy"]}},
  467. ),
  468. (
  469. "remove_jenny_from_tommy",
  470. {"friends_in_dict": {"Tommy": ["Jimmy"]}},
  471. ),
  472. (
  473. "tommy_has_no_fds",
  474. {"friends_in_dict": {"Tommy": []}},
  475. ),
  476. ],
  477. id="list in dict",
  478. ),
  479. ],
  480. )
  481. async def test_list_mutation_detection__plain_list(
  482. event_tuples: list[tuple[str, list[str]]],
  483. list_mutation_state: State,
  484. token: str,
  485. ):
  486. """Test list mutation detection
  487. when reassignment is not explicitly included in the logic.
  488. Args:
  489. event_tuples: From parametrization.
  490. list_mutation_state: A state with list mutation features.
  491. token: a Token.
  492. """
  493. for event_name, expected_delta in event_tuples:
  494. async for result in list_mutation_state._process(
  495. Event(
  496. token=token,
  497. name=f"{list_mutation_state.get_name()}.{event_name}",
  498. router_data={"pathname": "/", "query": {}},
  499. payload={},
  500. )
  501. ):
  502. # prefix keys in expected_delta with the state name
  503. expected_delta = {list_mutation_state.get_name(): expected_delta}
  504. assert result.delta == expected_delta
  505. @pytest.mark.asyncio
  506. @pytest.mark.parametrize(
  507. "event_tuples",
  508. [
  509. pytest.param(
  510. [
  511. (
  512. "add_age",
  513. {"details": {"name": "Tommy", "age": 20}},
  514. ),
  515. (
  516. "change_name",
  517. {"details": {"name": "Jenny", "age": 20}},
  518. ),
  519. (
  520. "remove_last_detail",
  521. {"details": {"name": "Jenny"}},
  522. ),
  523. ],
  524. id="update then __setitem__",
  525. ),
  526. pytest.param(
  527. [
  528. (
  529. "clear_details",
  530. {"details": {}},
  531. ),
  532. (
  533. "add_age",
  534. {"details": {"age": 20}},
  535. ),
  536. ],
  537. id="delitem then update",
  538. ),
  539. pytest.param(
  540. [
  541. (
  542. "add_age",
  543. {"details": {"name": "Tommy", "age": 20}},
  544. ),
  545. (
  546. "remove_name",
  547. {"details": {"age": 20}},
  548. ),
  549. (
  550. "pop_out_age",
  551. {"details": {}},
  552. ),
  553. ],
  554. id="add, remove, pop",
  555. ),
  556. pytest.param(
  557. [
  558. (
  559. "remove_home_address",
  560. {"address": [{}, {"work": "work address"}]},
  561. ),
  562. (
  563. "add_street_to_home_address",
  564. {
  565. "address": [
  566. {"street": "street address"},
  567. {"work": "work address"},
  568. ]
  569. },
  570. ),
  571. ],
  572. id="dict in list",
  573. ),
  574. pytest.param(
  575. [
  576. (
  577. "change_friend_name",
  578. {
  579. "friend_in_nested_dict": {
  580. "name": "Nikhil",
  581. "friend": {"name": "Tommy"},
  582. }
  583. },
  584. ),
  585. (
  586. "add_friend_age",
  587. {
  588. "friend_in_nested_dict": {
  589. "name": "Nikhil",
  590. "friend": {"name": "Tommy", "age": 30},
  591. }
  592. },
  593. ),
  594. (
  595. "remove_friend",
  596. {"friend_in_nested_dict": {"name": "Nikhil"}},
  597. ),
  598. ],
  599. id="nested dict",
  600. ),
  601. ],
  602. )
  603. async def test_dict_mutation_detection__plain_list(
  604. event_tuples: list[tuple[str, list[str]]],
  605. dict_mutation_state: State,
  606. token: str,
  607. ):
  608. """Test dict mutation detection
  609. when reassignment is not explicitly included in the logic.
  610. Args:
  611. event_tuples: From parametrization.
  612. dict_mutation_state: A state with dict mutation features.
  613. token: a Token.
  614. """
  615. for event_name, expected_delta in event_tuples:
  616. async for result in dict_mutation_state._process(
  617. Event(
  618. token=token,
  619. name=f"{dict_mutation_state.get_name()}.{event_name}",
  620. router_data={"pathname": "/", "query": {}},
  621. payload={},
  622. )
  623. ):
  624. # prefix keys in expected_delta with the state name
  625. expected_delta = {dict_mutation_state.get_name(): expected_delta}
  626. assert result.delta == expected_delta
  627. @pytest.mark.asyncio
  628. @pytest.mark.parametrize(
  629. ("state", "delta"),
  630. [
  631. (
  632. FileUploadState,
  633. {
  634. FileUploadState.get_full_name(): {
  635. "img_list": ["image1.jpg", "image2.jpg"]
  636. }
  637. },
  638. ),
  639. (
  640. ChildFileUploadState,
  641. {
  642. ChildFileUploadState.get_full_name(): {
  643. "img_list": ["image1.jpg", "image2.jpg"]
  644. }
  645. },
  646. ),
  647. (
  648. GrandChildFileUploadState,
  649. {
  650. GrandChildFileUploadState.get_full_name(): {
  651. "img_list": ["image1.jpg", "image2.jpg"]
  652. }
  653. },
  654. ),
  655. ],
  656. )
  657. async def test_upload_file(tmp_path, state, delta, token: str, mocker):
  658. """Test that file upload works correctly.
  659. Args:
  660. tmp_path: Temporary path.
  661. state: The state class.
  662. delta: Expected delta
  663. token: a Token.
  664. mocker: pytest mocker object.
  665. """
  666. mocker.patch(
  667. "reflex.state.State.class_subclasses",
  668. {state if state is FileUploadState else FileStateBase1},
  669. )
  670. state._tmp_path = tmp_path
  671. # The App state must be the "root" of the state tree
  672. app = App()
  673. app._enable_state()
  674. app.event_namespace.emit = AsyncMock() # pyright: ignore [reportOptionalMemberAccess]
  675. current_state = await app.state_manager.get_state(_substate_key(token, state))
  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. request_mock = unittest.mock.Mock()
  681. request_mock.headers = {
  682. "reflex-client-token": token,
  683. "reflex-event-handler": f"{state.get_full_name()}.multi_handle_upload",
  684. }
  685. file1 = UploadFile(
  686. filename="image1.jpg",
  687. file=bio,
  688. )
  689. file2 = UploadFile(
  690. filename="image2.jpg",
  691. file=bio,
  692. )
  693. upload_fn = upload(app)
  694. streaming_response = await upload_fn(request_mock, [file1, file2]) # pyright: ignore [reportFunctionMemberAccess]
  695. async for state_update in streaming_response.body_iterator:
  696. assert (
  697. state_update
  698. == StateUpdate(delta=delta, events=[], final=True).json() + "\n"
  699. )
  700. current_state = await app.state_manager.get_state(_substate_key(token, state))
  701. state_dict = current_state.dict()[state.get_full_name()]
  702. assert state_dict["img_list"] == [
  703. "image1.jpg",
  704. "image2.jpg",
  705. ]
  706. if isinstance(app.state_manager, StateManagerRedis):
  707. await app.state_manager.close()
  708. @pytest.mark.asyncio
  709. @pytest.mark.parametrize(
  710. "state",
  711. [FileUploadState, ChildFileUploadState, GrandChildFileUploadState],
  712. )
  713. async def test_upload_file_without_annotation(state, tmp_path, token):
  714. """Test that an error is thrown when there's no param annotated with rx.UploadFile or list[UploadFile].
  715. Args:
  716. state: The state class.
  717. tmp_path: Temporary path.
  718. token: a Token.
  719. """
  720. state._tmp_path = tmp_path
  721. app = App(_state=State)
  722. request_mock = unittest.mock.Mock()
  723. request_mock.headers = {
  724. "reflex-client-token": token,
  725. "reflex-event-handler": f"{state.get_full_name()}.handle_upload2",
  726. }
  727. file_mock = unittest.mock.Mock(filename="image1.jpg")
  728. fn = upload(app)
  729. with pytest.raises(ValueError) as err:
  730. await fn(request_mock, [file_mock])
  731. assert (
  732. err.value.args[0]
  733. == f"`{state.get_full_name()}.handle_upload2` handler should have a parameter annotated as list[rx.UploadFile]"
  734. )
  735. if isinstance(app.state_manager, StateManagerRedis):
  736. await app.state_manager.close()
  737. @pytest.mark.asyncio
  738. @pytest.mark.parametrize(
  739. "state",
  740. [FileUploadState, ChildFileUploadState, GrandChildFileUploadState],
  741. )
  742. async def test_upload_file_background(state, tmp_path, token):
  743. """Test that an error is thrown handler is a background task.
  744. Args:
  745. state: The state class.
  746. tmp_path: Temporary path.
  747. token: a Token.
  748. """
  749. state._tmp_path = tmp_path
  750. app = App(_state=State)
  751. request_mock = unittest.mock.Mock()
  752. request_mock.headers = {
  753. "reflex-client-token": token,
  754. "reflex-event-handler": f"{state.get_full_name()}.bg_upload",
  755. }
  756. file_mock = unittest.mock.Mock(filename="image1.jpg")
  757. fn = upload(app)
  758. with pytest.raises(TypeError) as err:
  759. await fn(request_mock, [file_mock])
  760. assert (
  761. err.value.args[0]
  762. == f"@rx.event(background=True) is not supported for upload handler `{state.get_full_name()}.bg_upload`."
  763. )
  764. if isinstance(app.state_manager, StateManagerRedis):
  765. await app.state_manager.close()
  766. class DynamicState(BaseState):
  767. """State class for testing dynamic route var.
  768. This is defined at module level because event handlers cannot be addressed
  769. correctly when the class is defined as a local.
  770. There are several counters:
  771. * loaded: counts how many times `on_load` was triggered by the hydrate middleware
  772. * counter: counts how many times `on_counter` was triggered by a non-navigational event
  773. -> these events should NOT trigger reload or recalculation of router_data dependent vars
  774. * side_effect_counter: counts how many times a computed var was
  775. recalculated when the dynamic route var was dirty
  776. """
  777. is_hydrated: bool = False
  778. loaded: int = 0
  779. counter: int = 0
  780. @rx.event
  781. def on_load(self):
  782. """Event handler for page on_load, should trigger for all navigation events."""
  783. self.loaded = self.loaded + 1
  784. @rx.event
  785. def on_counter(self):
  786. """Increment the counter var."""
  787. self.counter = self.counter + 1
  788. @computed_var
  789. def comp_dynamic(self) -> str:
  790. """A computed var that depends on the dynamic var.
  791. Returns:
  792. same as self.dynamic
  793. """
  794. return self.dynamic
  795. on_load_internal = OnLoadInternalState.on_load_internal.fn # pyright: ignore [reportFunctionMemberAccess]
  796. def test_dynamic_arg_shadow(
  797. index_page: ComponentCallable,
  798. windows_platform: bool,
  799. token: str,
  800. app_module_mock: unittest.mock.Mock,
  801. mocker,
  802. ):
  803. """Create app with dynamic route var and try to add a page with a dynamic arg that shadows a state var.
  804. Args:
  805. index_page: The index page.
  806. windows_platform: Whether the system is windows.
  807. token: a Token.
  808. app_module_mock: Mocked app module.
  809. mocker: pytest mocker object.
  810. """
  811. arg_name = "counter"
  812. route = f"/test/[{arg_name}]"
  813. app = app_module_mock.app = App(_state=DynamicState)
  814. assert app._state is not None
  815. with pytest.raises(NameError):
  816. app.add_page(index_page, route=route, on_load=DynamicState.on_load)
  817. def test_multiple_dynamic_args(
  818. index_page: ComponentCallable,
  819. windows_platform: bool,
  820. token: str,
  821. app_module_mock: unittest.mock.Mock,
  822. mocker,
  823. ):
  824. """Create app with multiple dynamic route vars with the same name.
  825. Args:
  826. index_page: The index page.
  827. windows_platform: Whether the system is windows.
  828. token: a Token.
  829. app_module_mock: Mocked app module.
  830. mocker: pytest mocker object.
  831. """
  832. arg_name = "my_arg"
  833. route = f"/test/[{arg_name}]"
  834. route2 = f"/test2/[{arg_name}]"
  835. app = app_module_mock.app = App(_state=EmptyState)
  836. app.add_page(index_page, route=route)
  837. app.add_page(index_page, route=route2)
  838. @pytest.mark.asyncio
  839. async def test_dynamic_route_var_route_change_completed_on_load(
  840. index_page: ComponentCallable,
  841. windows_platform: bool,
  842. token: str,
  843. app_module_mock: unittest.mock.Mock,
  844. mocker,
  845. ):
  846. """Create app with dynamic route var, and simulate navigation.
  847. on_load should fire, allowing any additional vars to be updated before the
  848. initial page hydrate.
  849. Args:
  850. index_page: The index page.
  851. windows_platform: Whether the system is windows.
  852. token: a Token.
  853. app_module_mock: Mocked app module.
  854. mocker: pytest mocker object.
  855. """
  856. arg_name = "dynamic"
  857. route = f"/test/[{arg_name}]"
  858. app = app_module_mock.app = App(_state=DynamicState)
  859. assert app._state is not None
  860. assert arg_name not in app._state.vars
  861. app.add_page(index_page, route=route, on_load=DynamicState.on_load)
  862. assert arg_name in app._state.vars
  863. assert arg_name in app._state.computed_vars
  864. assert app._state.computed_vars[arg_name]._deps(objclass=DynamicState) == {
  865. DynamicState.get_full_name(): {constants.ROUTER},
  866. }
  867. assert constants.ROUTER in app._state()._var_dependencies
  868. substate_token = _substate_key(token, DynamicState)
  869. sid = "mock_sid"
  870. client_ip = "127.0.0.1"
  871. async with app.state_manager.modify_state(substate_token) as state:
  872. state.router_data = {"simulate": "hydrated"}
  873. assert state.dynamic == ""
  874. exp_vals = ["foo", "foobar", "baz"]
  875. def _event(name, val, **kwargs):
  876. return Event(
  877. token=kwargs.pop("token", token),
  878. name=name,
  879. router_data=kwargs.pop(
  880. "router_data", {"pathname": route, "query": {arg_name: val}}
  881. ),
  882. payload=kwargs.pop("payload", {}),
  883. **kwargs,
  884. )
  885. def _dynamic_state_event(name, val, **kwargs):
  886. return _event(
  887. name=format.format_event_handler(getattr(DynamicState, name)),
  888. val=val,
  889. **kwargs,
  890. )
  891. prev_exp_val = ""
  892. for exp_index, exp_val in enumerate(exp_vals):
  893. on_load_internal = _event(
  894. name=f"{state.get_full_name()}.{constants.CompileVars.ON_LOAD_INTERNAL.rpartition('.')[2]}",
  895. val=exp_val,
  896. )
  897. exp_router_data = {
  898. "headers": {},
  899. "ip": client_ip,
  900. "sid": sid,
  901. "token": token,
  902. **on_load_internal.router_data,
  903. }
  904. exp_router = RouterData(exp_router_data)
  905. process_coro = process(
  906. app,
  907. event=on_load_internal,
  908. sid=sid,
  909. headers={},
  910. client_ip=client_ip,
  911. )
  912. update = await process_coro.__anext__()
  913. # route change (on_load_internal) triggers: [call on_load events, call set_is_hydrated(True)]
  914. assert update == StateUpdate(
  915. delta={
  916. state.get_name(): {
  917. arg_name: exp_val,
  918. f"comp_{arg_name}": exp_val,
  919. constants.CompileVars.IS_HYDRATED: False,
  920. "router": exp_router,
  921. }
  922. },
  923. events=[
  924. _dynamic_state_event(
  925. name="on_load",
  926. val=exp_val,
  927. ),
  928. _event(
  929. name=f"{State.get_name()}.set_is_hydrated",
  930. payload={"value": True},
  931. val=exp_val,
  932. router_data={},
  933. ),
  934. ],
  935. )
  936. if isinstance(app.state_manager, StateManagerRedis):
  937. # When redis is used, the state is not updated until the processing is complete
  938. state = await app.state_manager.get_state(substate_token)
  939. assert state.dynamic == prev_exp_val
  940. # complete the processing
  941. with pytest.raises(StopAsyncIteration):
  942. await process_coro.__anext__()
  943. # check that router data was written to the state_manager store
  944. state = await app.state_manager.get_state(substate_token)
  945. assert state.dynamic == exp_val
  946. process_coro = process(
  947. app,
  948. event=_dynamic_state_event(name="on_load", val=exp_val),
  949. sid=sid,
  950. headers={},
  951. client_ip=client_ip,
  952. )
  953. on_load_update = await process_coro.__anext__()
  954. assert on_load_update == StateUpdate(
  955. delta={
  956. state.get_name(): {
  957. "loaded": exp_index + 1,
  958. },
  959. },
  960. events=[],
  961. )
  962. # complete the processing
  963. with pytest.raises(StopAsyncIteration):
  964. await process_coro.__anext__()
  965. process_coro = process(
  966. app,
  967. event=_dynamic_state_event(
  968. name="set_is_hydrated", payload={"value": True}, val=exp_val
  969. ),
  970. sid=sid,
  971. headers={},
  972. client_ip=client_ip,
  973. )
  974. on_set_is_hydrated_update = await process_coro.__anext__()
  975. assert on_set_is_hydrated_update == StateUpdate(
  976. delta={
  977. state.get_name(): {
  978. "is_hydrated": True,
  979. },
  980. },
  981. events=[],
  982. )
  983. # complete the processing
  984. with pytest.raises(StopAsyncIteration):
  985. await process_coro.__anext__()
  986. # a simple state update event should NOT trigger on_load or route var side effects
  987. process_coro = process(
  988. app,
  989. event=_dynamic_state_event(name="on_counter", val=exp_val),
  990. sid=sid,
  991. headers={},
  992. client_ip=client_ip,
  993. )
  994. update = await process_coro.__anext__()
  995. assert update == StateUpdate(
  996. delta={
  997. state.get_name(): {
  998. "counter": exp_index + 1,
  999. }
  1000. },
  1001. events=[],
  1002. )
  1003. # complete the processing
  1004. with pytest.raises(StopAsyncIteration):
  1005. await process_coro.__anext__()
  1006. prev_exp_val = exp_val
  1007. state = await app.state_manager.get_state(substate_token)
  1008. assert state.loaded == len(exp_vals)
  1009. assert state.counter == len(exp_vals)
  1010. if isinstance(app.state_manager, StateManagerRedis):
  1011. await app.state_manager.close()
  1012. @pytest.mark.asyncio
  1013. async def test_process_events(mocker, token: str):
  1014. """Test that an event is processed properly and that it is postprocessed
  1015. n+1 times. Also check that the processing flag of the last stateupdate is set to
  1016. False.
  1017. Args:
  1018. mocker: mocker object.
  1019. token: a Token.
  1020. """
  1021. router_data = {
  1022. "pathname": "/",
  1023. "query": {},
  1024. "token": token,
  1025. "sid": "mock_sid",
  1026. "headers": {},
  1027. "ip": "127.0.0.1",
  1028. }
  1029. app = App(_state=GenState)
  1030. mocker.patch.object(app, "_postprocess", AsyncMock())
  1031. event = Event(
  1032. token=token,
  1033. name=f"{GenState.get_name()}.go",
  1034. payload={"c": 5},
  1035. router_data=router_data,
  1036. )
  1037. async with app.state_manager.modify_state(event.substate_token) as state:
  1038. state.router_data = {"simulate": "hydrated"}
  1039. async for _update in process(app, event, "mock_sid", {}, "127.0.0.1"):
  1040. pass
  1041. assert (await app.state_manager.get_state(event.substate_token)).value == 5
  1042. assert app._postprocess.call_count == 6 # pyright: ignore [reportFunctionMemberAccess]
  1043. if isinstance(app.state_manager, StateManagerRedis):
  1044. await app.state_manager.close()
  1045. @pytest.mark.parametrize(
  1046. ("state", "overlay_component", "exp_page_child"),
  1047. [
  1048. (None, default_overlay_component, None),
  1049. (None, None, None),
  1050. (None, Text.create("foo"), Text),
  1051. (State, default_overlay_component, Fragment),
  1052. (State, None, None),
  1053. (State, Text.create("foo"), Text),
  1054. (State, lambda: Text.create("foo"), Text),
  1055. ],
  1056. )
  1057. def test_overlay_component(
  1058. state: type[State] | None,
  1059. overlay_component: Component | ComponentCallable | None,
  1060. exp_page_child: type[Component] | None,
  1061. ):
  1062. """Test that the overlay component is set correctly.
  1063. Args:
  1064. state: The state class to pass to App.
  1065. overlay_component: The overlay_component to pass to App.
  1066. exp_page_child: The type of the expected child in the page fragment.
  1067. """
  1068. app = App(_state=state, overlay_component=overlay_component)
  1069. app._setup_overlay_component()
  1070. if exp_page_child is None:
  1071. assert app.overlay_component is None
  1072. elif isinstance(exp_page_child, OverlayFragment):
  1073. assert app.overlay_component is not None
  1074. generated_component = app._generate_component(app.overlay_component)
  1075. assert isinstance(generated_component, OverlayFragment)
  1076. assert isinstance(
  1077. generated_component.children[0],
  1078. Cond, # ConnectionModal is a Cond under the hood
  1079. )
  1080. else:
  1081. assert app.overlay_component is not None
  1082. assert isinstance(
  1083. app._generate_component(app.overlay_component),
  1084. exp_page_child,
  1085. )
  1086. app.add_page(rx.box("Index"), route="/test")
  1087. # overlay components are wrapped during compile only
  1088. app._compile_page("test")
  1089. app._setup_overlay_component()
  1090. page = app._pages["test"]
  1091. if exp_page_child is not None:
  1092. assert len(page.children) == 3
  1093. children_types = (type(child) for child in page.children)
  1094. assert exp_page_child in children_types # pyright: ignore [reportOperatorIssue]
  1095. else:
  1096. assert len(page.children) == 2
  1097. @pytest.fixture
  1098. def compilable_app(tmp_path) -> Generator[tuple[App, Path], None, None]:
  1099. """Fixture for an app that can be compiled.
  1100. Args:
  1101. tmp_path: Temporary path.
  1102. Yields:
  1103. Tuple containing (app instance, Path to ".web" directory)
  1104. The working directory is set to the app dir (parent of .web),
  1105. allowing app.compile() to be called.
  1106. """
  1107. app_path = tmp_path / "app"
  1108. web_dir = app_path / ".web"
  1109. web_dir.mkdir(parents=True)
  1110. (web_dir / constants.PackageJson.PATH).touch()
  1111. (web_dir / constants.Dirs.POSTCSS_JS).touch()
  1112. (web_dir / constants.Dirs.POSTCSS_JS).write_text(
  1113. """
  1114. module.exports = {
  1115. plugins: {
  1116. "postcss-import": {},
  1117. autoprefixer: {},
  1118. },
  1119. };
  1120. """,
  1121. )
  1122. app = App(theme=None)
  1123. app._get_frontend_packages = unittest.mock.Mock()
  1124. with chdir(app_path):
  1125. yield app, web_dir
  1126. @pytest.mark.parametrize(
  1127. "react_strict_mode",
  1128. [True, False],
  1129. )
  1130. def test_app_wrap_compile_theme(
  1131. react_strict_mode: bool, compilable_app: tuple[App, Path], mocker
  1132. ):
  1133. """Test that the radix theme component wraps the app.
  1134. Args:
  1135. react_strict_mode: Whether to use React Strict Mode.
  1136. compilable_app: compilable_app fixture.
  1137. mocker: pytest mocker object.
  1138. """
  1139. conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode)
  1140. mocker.patch("reflex.config._get_config", return_value=conf)
  1141. app, web_dir = compilable_app
  1142. mocker.patch("reflex.utils.prerequisites.get_web_dir", return_value=web_dir)
  1143. app.theme = rx.theme(accent_color="plum")
  1144. app._compile()
  1145. app_js_contents = (web_dir / "pages" / "_app.js").read_text()
  1146. app_js_lines = [
  1147. line.strip() for line in app_js_contents.splitlines() if line.strip()
  1148. ]
  1149. lines = "".join(app_js_lines)
  1150. assert (
  1151. "function AppWrap({children}) {"
  1152. "return ("
  1153. + ("<StrictMode>" if react_strict_mode else "")
  1154. + "<RadixThemesColorModeProvider>"
  1155. "<RadixThemesTheme accentColor={\"plum\"} css={{...theme.styles.global[':root'], ...theme.styles.global.body}}>"
  1156. "<Fragment>"
  1157. "<MemoizedToastProvider/>"
  1158. "<Fragment>"
  1159. "{children}"
  1160. "</Fragment>"
  1161. "</Fragment>"
  1162. "</RadixThemesTheme>"
  1163. "</RadixThemesColorModeProvider>"
  1164. + ("</StrictMode>" if react_strict_mode else "")
  1165. + ")"
  1166. "}"
  1167. ) in lines
  1168. @pytest.mark.parametrize(
  1169. "react_strict_mode",
  1170. [True, False],
  1171. )
  1172. def test_app_wrap_priority(
  1173. react_strict_mode: bool, compilable_app: tuple[App, Path], mocker
  1174. ):
  1175. """Test that the app wrap components are wrapped in the correct order.
  1176. Args:
  1177. react_strict_mode: Whether to use React Strict Mode.
  1178. compilable_app: compilable_app fixture.
  1179. mocker: pytest mocker object.
  1180. """
  1181. conf = rx.Config(app_name="testing", react_strict_mode=react_strict_mode)
  1182. mocker.patch("reflex.config._get_config", return_value=conf)
  1183. app, web_dir = compilable_app
  1184. class Fragment1(Component):
  1185. tag = "Fragment1"
  1186. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride]
  1187. return {(99, "Box"): rx.box()}
  1188. class Fragment2(Component):
  1189. tag = "Fragment2"
  1190. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride]
  1191. return {(50, "Text"): rx.text()}
  1192. class Fragment3(Component):
  1193. tag = "Fragment3"
  1194. def _get_app_wrap_components(self) -> dict[tuple[int, str], Component]: # pyright: ignore [reportIncompatibleMethodOverride]
  1195. return {(10, "Fragment2"): Fragment2.create()}
  1196. def page():
  1197. return Fragment1.create(Fragment3.create())
  1198. app.add_page(page)
  1199. app._compile()
  1200. app_js_contents = (web_dir / "pages" / "_app.js").read_text()
  1201. app_js_lines = [
  1202. line.strip() for line in app_js_contents.splitlines() if line.strip()
  1203. ]
  1204. lines = "".join(app_js_lines)
  1205. assert (
  1206. "function AppWrap({children}) {"
  1207. "return (" + ("<StrictMode>" if react_strict_mode else "") + "<RadixThemesBox>"
  1208. '<RadixThemesText as={"p"}>'
  1209. "<RadixThemesColorModeProvider>"
  1210. "<Fragment2>"
  1211. "<Fragment>"
  1212. "<MemoizedToastProvider/>"
  1213. "<Fragment>"
  1214. "{children}"
  1215. "</Fragment>"
  1216. "</Fragment>"
  1217. "</Fragment2>"
  1218. "</RadixThemesColorModeProvider>"
  1219. "</RadixThemesText>"
  1220. "</RadixThemesBox>" + ("</StrictMode>" if react_strict_mode else "")
  1221. ) in lines
  1222. def test_app_state_determination():
  1223. """Test that the stateless status of an app is determined correctly."""
  1224. a1 = App()
  1225. assert a1._state is None
  1226. # No state, no router, no event handlers.
  1227. a1.add_page(rx.box("Index"), route="/")
  1228. assert a1._state is None
  1229. # Add a page with `on_load` enables state.
  1230. a1.add_page(rx.box("About"), route="/about", on_load=rx.console_log(""))
  1231. a1._compile_page("about")
  1232. assert a1._state is not None
  1233. a2 = App()
  1234. assert a2._state is None
  1235. # Referencing a state Var enables state.
  1236. a2.add_page(rx.box(rx.text(GenState.value)), route="/")
  1237. a2._compile_page("index")
  1238. assert a2._state is not None
  1239. a3 = App()
  1240. assert a3._state is None
  1241. # Referencing router enables state.
  1242. a3.add_page(rx.box(rx.text(State.router.page.full_path)), route="/")
  1243. a3._compile_page("index")
  1244. assert a3._state is not None
  1245. a4 = App()
  1246. assert a4._state is None
  1247. a4.add_page(rx.box(rx.button("Click", on_click=rx.console_log(""))), route="/")
  1248. assert a4._state is None
  1249. a4.add_page(
  1250. rx.box(rx.button("Click", on_click=DynamicState.on_counter)), route="/page2"
  1251. )
  1252. a4._compile_page("page2")
  1253. assert a4._state is not None
  1254. def test_raise_on_state():
  1255. """Test that the state is set."""
  1256. # state kwargs is deprecated, we just make sure the app is created anyway.
  1257. _app = App(_state=State)
  1258. assert _app._state is not None
  1259. assert issubclass(_app._state, State)
  1260. def test_call_app():
  1261. """Test that the app can be called."""
  1262. app = App()
  1263. app._get_frontend_packages = unittest.mock.Mock()
  1264. api = app()
  1265. assert isinstance(api, FastAPI)
  1266. def test_app_with_optional_endpoints():
  1267. from reflex.components.core.upload import Upload
  1268. app = App()
  1269. Upload.is_used = True
  1270. app._add_optional_endpoints()
  1271. # TODO: verify the availability of the endpoints in app.api
  1272. def test_app_state_manager():
  1273. app = App()
  1274. with pytest.raises(ValueError):
  1275. app.state_manager
  1276. app._enable_state()
  1277. assert app.state_manager is not None
  1278. assert isinstance(
  1279. app.state_manager, (StateManagerMemory, StateManagerDisk, StateManagerRedis)
  1280. )
  1281. def test_generate_component():
  1282. def index():
  1283. return rx.box("Index")
  1284. def index_mismatch():
  1285. return rx.match(
  1286. 1,
  1287. (1, rx.box("Index")),
  1288. (2, "About"),
  1289. "Bar",
  1290. )
  1291. comp = App._generate_component(index)
  1292. assert isinstance(comp, Component)
  1293. with pytest.raises(exceptions.MatchTypeError):
  1294. App._generate_component(index_mismatch)
  1295. def test_add_page_component_returning_tuple():
  1296. """Test that a component or render method returning a
  1297. tuple is unpacked in a Fragment.
  1298. """
  1299. app = App()
  1300. def index():
  1301. return rx.text("first"), rx.text("second")
  1302. def page2():
  1303. return (rx.text("third"),)
  1304. app.add_page(index)
  1305. app.add_page(page2)
  1306. app._compile_page("index")
  1307. app._compile_page("page2")
  1308. fragment_wrapper = app._pages["index"].children[0]
  1309. assert isinstance(fragment_wrapper, Fragment)
  1310. first_text = fragment_wrapper.children[0]
  1311. assert isinstance(first_text, Text)
  1312. assert isinstance(first_text.children[0], Bare)
  1313. assert str(first_text.children[0].contents) == '"first"'
  1314. second_text = fragment_wrapper.children[1]
  1315. assert isinstance(second_text, Text)
  1316. assert isinstance(second_text.children[0], Bare)
  1317. assert str(second_text.children[0].contents) == '"second"'
  1318. # Test page with trailing comma.
  1319. page2_fragment_wrapper = app._pages["page2"].children[0]
  1320. assert isinstance(page2_fragment_wrapper, Fragment)
  1321. third_text = page2_fragment_wrapper.children[0]
  1322. assert isinstance(third_text, Text)
  1323. assert isinstance(third_text.children[0], Bare)
  1324. assert str(third_text.children[0].contents) == '"third"'
  1325. @pytest.mark.parametrize("export", (True, False))
  1326. def test_app_with_transpile_packages(compilable_app: tuple[App, Path], export: bool):
  1327. class C1(rx.Component):
  1328. library = "foo@1.2.3"
  1329. tag = "Foo"
  1330. transpile_packages: list[str] = ["foo"]
  1331. class C2(rx.Component):
  1332. library = "bar@4.5.6"
  1333. tag = "Bar"
  1334. transpile_packages: list[str] = ["bar@4.5.6"]
  1335. class C3(rx.NoSSRComponent):
  1336. library = "baz@7.8.10"
  1337. tag = "Baz"
  1338. transpile_packages: list[str] = ["baz@7.8.9"]
  1339. class C4(rx.NoSSRComponent):
  1340. library = "quuc@2.3.4"
  1341. tag = "Quuc"
  1342. transpile_packages: list[str] = ["quuc"]
  1343. class C5(rx.Component):
  1344. library = "quuc"
  1345. tag = "Quuc"
  1346. app, web_dir = compilable_app
  1347. page = Fragment.create(
  1348. C1.create(), C2.create(), C3.create(), C4.create(), C5.create()
  1349. )
  1350. app.add_page(page, route="/")
  1351. app._compile(export=export)
  1352. next_config = (web_dir / "next.config.js").read_text()
  1353. transpile_packages_match = re.search(r"transpilePackages: (\[.*?\])", next_config)
  1354. transpile_packages_json = transpile_packages_match.group(1) # pyright: ignore [reportOptionalMemberAccess]
  1355. transpile_packages = sorted(json.loads(transpile_packages_json))
  1356. assert transpile_packages == [
  1357. "bar",
  1358. "foo",
  1359. "quuc",
  1360. ]
  1361. if export:
  1362. assert 'output: "export"' in next_config
  1363. assert f'distDir: "{constants.Dirs.STATIC}"' in next_config
  1364. else:
  1365. assert 'output: "export"' not in next_config
  1366. assert f'distDir: "{constants.Dirs.STATIC}"' not in next_config
  1367. def test_app_with_valid_var_dependencies(compilable_app: tuple[App, Path]):
  1368. app, _ = compilable_app
  1369. class ValidDepState(BaseState):
  1370. base: int = 0
  1371. _backend: int = 0
  1372. @computed_var()
  1373. def foo(self) -> str:
  1374. return "foo"
  1375. @computed_var(deps=["_backend", "base", foo])
  1376. def bar(self) -> str:
  1377. return "bar"
  1378. class Child1(ValidDepState):
  1379. @computed_var(deps=["base", ValidDepState.bar])
  1380. def other(self) -> str:
  1381. return "other"
  1382. class Child2(ValidDepState):
  1383. @computed_var(deps=["base", Child1.other])
  1384. def other(self) -> str:
  1385. return "other"
  1386. app._state = ValidDepState
  1387. app._compile()
  1388. def test_app_with_invalid_var_dependencies(compilable_app: tuple[App, Path]):
  1389. app, _ = compilable_app
  1390. class InvalidDepState(BaseState):
  1391. @computed_var(deps=["foolksjdf"])
  1392. def bar(self) -> str:
  1393. return "bar"
  1394. app._state = InvalidDepState
  1395. with pytest.raises(exceptions.VarDependencyError):
  1396. app._compile()
  1397. # Test custom exception handlers
  1398. def valid_custom_handler(exception: Exception, logger: str = "test"):
  1399. print("Custom Backend Exception")
  1400. print(exception)
  1401. def custom_exception_handler_with_wrong_arg_order(
  1402. logger: str,
  1403. exception: Exception, # Should be first
  1404. ):
  1405. print("Custom Backend Exception")
  1406. print(exception)
  1407. def custom_exception_handler_with_wrong_argspec(
  1408. exception: str, # Should be Exception
  1409. ):
  1410. print("Custom Backend Exception")
  1411. print(exception)
  1412. class DummyExceptionHandler:
  1413. """Dummy exception handler class."""
  1414. def handle(self, exception: Exception):
  1415. """Handle the exception.
  1416. Args:
  1417. exception: The exception.
  1418. """
  1419. print("Custom Backend Exception")
  1420. print(exception)
  1421. custom_exception_handlers = {
  1422. "lambda": lambda exception: print("Custom Exception Handler", exception),
  1423. "wrong_argspec": custom_exception_handler_with_wrong_argspec,
  1424. "wrong_arg_order": custom_exception_handler_with_wrong_arg_order,
  1425. "valid": valid_custom_handler,
  1426. "partial": functools.partial(valid_custom_handler, logger="test"),
  1427. "method": DummyExceptionHandler().handle,
  1428. }
  1429. @pytest.mark.parametrize(
  1430. "handler_fn, expected",
  1431. [
  1432. pytest.param(
  1433. custom_exception_handlers["partial"],
  1434. pytest.raises(ValueError),
  1435. id="partial",
  1436. ),
  1437. pytest.param(
  1438. custom_exception_handlers["lambda"],
  1439. pytest.raises(ValueError),
  1440. id="lambda",
  1441. ),
  1442. pytest.param(
  1443. custom_exception_handlers["wrong_argspec"],
  1444. pytest.raises(ValueError),
  1445. id="wrong_argspec",
  1446. ),
  1447. pytest.param(
  1448. custom_exception_handlers["wrong_arg_order"],
  1449. pytest.raises(ValueError),
  1450. id="wrong_arg_order",
  1451. ),
  1452. pytest.param(
  1453. custom_exception_handlers["valid"],
  1454. does_not_raise(),
  1455. id="valid_handler",
  1456. ),
  1457. pytest.param(
  1458. custom_exception_handlers["method"],
  1459. does_not_raise(),
  1460. id="valid_class_method",
  1461. ),
  1462. ],
  1463. )
  1464. def test_frontend_exception_handler_validation(handler_fn, expected):
  1465. """Test that the custom frontend exception handler is properly validated.
  1466. Args:
  1467. handler_fn: The handler function.
  1468. expected: The expected result.
  1469. """
  1470. with expected:
  1471. rx.App(frontend_exception_handler=handler_fn)._validate_exception_handlers()
  1472. def backend_exception_handler_with_wrong_return_type(exception: Exception) -> int:
  1473. """Custom backend exception handler with wrong return type.
  1474. Args:
  1475. exception: The exception.
  1476. Returns:
  1477. int: The wrong return type.
  1478. """
  1479. print("Custom Backend Exception")
  1480. print(exception)
  1481. return 5
  1482. @pytest.mark.parametrize(
  1483. "handler_fn, expected",
  1484. [
  1485. pytest.param(
  1486. backend_exception_handler_with_wrong_return_type,
  1487. pytest.raises(ValueError),
  1488. id="wrong_return_type",
  1489. ),
  1490. pytest.param(
  1491. custom_exception_handlers["partial"],
  1492. pytest.raises(ValueError),
  1493. id="partial",
  1494. ),
  1495. pytest.param(
  1496. custom_exception_handlers["lambda"],
  1497. pytest.raises(ValueError),
  1498. id="lambda",
  1499. ),
  1500. pytest.param(
  1501. custom_exception_handlers["wrong_argspec"],
  1502. pytest.raises(ValueError),
  1503. id="wrong_argspec",
  1504. ),
  1505. pytest.param(
  1506. custom_exception_handlers["wrong_arg_order"],
  1507. pytest.raises(ValueError),
  1508. id="wrong_arg_order",
  1509. ),
  1510. pytest.param(
  1511. custom_exception_handlers["valid"],
  1512. does_not_raise(),
  1513. id="valid_handler",
  1514. ),
  1515. pytest.param(
  1516. custom_exception_handlers["method"],
  1517. does_not_raise(),
  1518. id="valid_class_method",
  1519. ),
  1520. ],
  1521. )
  1522. def test_backend_exception_handler_validation(handler_fn, expected):
  1523. """Test that the custom backend exception handler is properly validated.
  1524. Args:
  1525. handler_fn: The handler function.
  1526. expected: The expected result.
  1527. """
  1528. with expected:
  1529. rx.App(backend_exception_handler=handler_fn)._validate_exception_handlers()