test_app.py 52 KB

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