test_app.py 41 KB

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