test_app.py 49 KB

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