test_app.py 24 KB

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