test_app.py 45 KB

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