test_app.py 49 KB

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