test_app.py 27 KB

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