test_app.py 48 KB

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