test_app.py 48 KB

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