test_app.py 38 KB

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