test_app.py 48 KB

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