test_app.py 29 KB

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