test_app.py 34 KB

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