test_app.py 22 KB

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