test_app.py 39 KB

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