test_app.py 37 KB

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