test_app.py 45 KB

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