test_app.py 38 KB

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