1
0

test_app.py 51 KB

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