test_app.py 25 KB

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