test_app.py 39 KB

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