test_app.py 37 KB

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