test_app.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  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.app import App, DefaultState, upload
  7. from pynecone.components import Box
  8. from pynecone.event import Event
  9. from pynecone.middleware import HydrateMiddleware
  10. from pynecone.state import State, StateUpdate
  11. from pynecone.style import Style
  12. @pytest.fixture
  13. def app() -> App:
  14. """A base app.
  15. Returns:
  16. The app.
  17. """
  18. return App()
  19. @pytest.fixture
  20. def index_page():
  21. """An index page.
  22. Returns:
  23. The index page.
  24. """
  25. def index():
  26. return Box.create("Index")
  27. return index
  28. @pytest.fixture
  29. def about_page():
  30. """An about page.
  31. Returns:
  32. The about page.
  33. """
  34. def about():
  35. return Box.create("About")
  36. return about
  37. @pytest.fixture()
  38. def test_state() -> Type[State]:
  39. """A default state.
  40. Returns:
  41. A default state.
  42. """
  43. class TestState(State):
  44. var: int
  45. return TestState
  46. def test_default_app(app: App):
  47. """Test creating an app with no args.
  48. Args:
  49. app: The app to test.
  50. """
  51. assert app.state() == DefaultState()
  52. assert app.middleware == [HydrateMiddleware()]
  53. assert app.style == Style()
  54. def test_add_page_default_route(app: App, index_page, about_page):
  55. """Test adding a page to an app.
  56. Args:
  57. app: The app to test.
  58. index_page: The index page.
  59. about_page: The about page.
  60. """
  61. assert app.pages == {}
  62. app.add_page(index_page)
  63. assert set(app.pages.keys()) == {"index"}
  64. app.add_page(about_page)
  65. assert set(app.pages.keys()) == {"index", "about"}
  66. def test_add_page_set_route(app: App, index_page, windows_platform: bool):
  67. """Test adding a page to an app.
  68. Args:
  69. app: The app to test.
  70. index_page: The index page.
  71. windows_platform: Whether the system is windows.
  72. """
  73. route = "test" if windows_platform else "/test"
  74. assert app.pages == {}
  75. app.add_page(index_page, route=route)
  76. assert set(app.pages.keys()) == {"test"}
  77. def test_add_page_set_route_nested(app: App, index_page, windows_platform: bool):
  78. """Test adding a page to an app.
  79. Args:
  80. app: The app to test.
  81. index_page: The index page.
  82. windows_platform: Whether the system is windows.
  83. """
  84. route = "test\\nested" if windows_platform else "/test/nested"
  85. assert app.pages == {}
  86. app.add_page(index_page, route=route)
  87. assert set(app.pages.keys()) == {route.strip(os.path.sep)}
  88. def test_initialize_with_state(test_state):
  89. """Test setting the state of an app.
  90. Args:
  91. test_state: The default state.
  92. """
  93. app = App(state=test_state)
  94. assert app.state == test_state
  95. # Get a state for a given token.
  96. token = "token"
  97. state = app.state_manager.get_state(token)
  98. assert isinstance(state, test_state)
  99. assert state.var == 0 # type: ignore
  100. def test_set_and_get_state(test_state):
  101. """Test setting and getting the state of an app with different tokens.
  102. Args:
  103. test_state: The default state.
  104. """
  105. app = App(state=test_state)
  106. # Create two tokens.
  107. token1 = "token1"
  108. token2 = "token2"
  109. # Get the default state for each token.
  110. state1 = app.state_manager.get_state(token1)
  111. state2 = app.state_manager.get_state(token2)
  112. assert state1.var == 0 # type: ignore
  113. assert state2.var == 0 # type: ignore
  114. # Set the vars to different values.
  115. state1.var = 1
  116. state2.var = 2
  117. app.state_manager.set_state(token1, state1)
  118. app.state_manager.set_state(token2, state2)
  119. # Get the states again and check the values.
  120. state1 = app.state_manager.get_state(token1)
  121. state2 = app.state_manager.get_state(token2)
  122. assert state1.var == 1 # type: ignore
  123. assert state2.var == 2 # type: ignore
  124. @pytest.mark.asyncio
  125. async def test_dynamic_var_event(test_state):
  126. """Test that the default handler of a dynamic generated var
  127. works as expected.
  128. Args:
  129. test_state: State Fixture.
  130. """
  131. test_state = test_state()
  132. test_state.add_var("int_val", int, 0)
  133. result = await test_state._process(
  134. Event(
  135. token="fake-token",
  136. name="test_state.set_int_val",
  137. router_data={"pathname": "/", "query": {}},
  138. payload={"value": 50},
  139. )
  140. )
  141. assert result.delta == {"test_state": {"int_val": 50}}
  142. @pytest.mark.asyncio
  143. @pytest.mark.parametrize(
  144. "event_tuples",
  145. [
  146. pytest.param(
  147. [
  148. (
  149. "test_state.make_friend",
  150. {"test_state": {"plain_friends": ["Tommy", "another-fd"]}},
  151. ),
  152. (
  153. "test_state.change_first_friend",
  154. {"test_state": {"plain_friends": ["Jenny", "another-fd"]}},
  155. ),
  156. ],
  157. id="append then __setitem__",
  158. ),
  159. pytest.param(
  160. [
  161. (
  162. "test_state.unfriend_first_friend",
  163. {"test_state": {"plain_friends": []}},
  164. ),
  165. (
  166. "test_state.make_friend",
  167. {"test_state": {"plain_friends": ["another-fd"]}},
  168. ),
  169. ],
  170. id="delitem then append",
  171. ),
  172. pytest.param(
  173. [
  174. (
  175. "test_state.make_friends_with_colleagues",
  176. {"test_state": {"plain_friends": ["Tommy", "Peter", "Jimmy"]}},
  177. ),
  178. (
  179. "test_state.remove_tommy",
  180. {"test_state": {"plain_friends": ["Peter", "Jimmy"]}},
  181. ),
  182. (
  183. "test_state.remove_last_friend",
  184. {"test_state": {"plain_friends": ["Peter"]}},
  185. ),
  186. (
  187. "test_state.unfriend_all_friends",
  188. {"test_state": {"plain_friends": []}},
  189. ),
  190. ],
  191. id="extend, remove, pop, clear",
  192. ),
  193. pytest.param(
  194. [
  195. (
  196. "test_state.add_jimmy_to_second_group",
  197. {
  198. "test_state": {
  199. "friends_in_nested_list": [["Tommy"], ["Jenny", "Jimmy"]]
  200. }
  201. },
  202. ),
  203. (
  204. "test_state.remove_first_person_from_first_group",
  205. {
  206. "test_state": {
  207. "friends_in_nested_list": [[], ["Jenny", "Jimmy"]]
  208. }
  209. },
  210. ),
  211. (
  212. "test_state.remove_first_group",
  213. {"test_state": {"friends_in_nested_list": [["Jenny", "Jimmy"]]}},
  214. ),
  215. ],
  216. id="nested list",
  217. ),
  218. pytest.param(
  219. [
  220. (
  221. "test_state.add_jimmy_to_tommy_friends",
  222. {"test_state": {"friends_in_dict": {"Tommy": ["Jenny", "Jimmy"]}}},
  223. ),
  224. (
  225. "test_state.remove_jenny_from_tommy",
  226. {"test_state": {"friends_in_dict": {"Tommy": ["Jimmy"]}}},
  227. ),
  228. (
  229. "test_state.tommy_has_no_fds",
  230. {"test_state": {"friends_in_dict": {"Tommy": []}}},
  231. ),
  232. ],
  233. id="list in dict",
  234. ),
  235. ],
  236. )
  237. async def test_list_mutation_detection__plain_list(
  238. event_tuples: List[Tuple[str, List[str]]], list_mutation_state: State
  239. ):
  240. """Test list mutation detection
  241. when reassignment is not explicitly included in the logic.
  242. Args:
  243. event_tuples: From parametrization.
  244. list_mutation_state: A state with list mutation features.
  245. """
  246. for event_name, expected_delta in event_tuples:
  247. result = await list_mutation_state._process(
  248. Event(
  249. token="fake-token",
  250. name=event_name,
  251. router_data={"pathname": "/", "query": {}},
  252. payload={},
  253. )
  254. )
  255. assert result.delta == expected_delta
  256. @pytest.mark.asyncio
  257. @pytest.mark.parametrize(
  258. "event_tuples",
  259. [
  260. pytest.param(
  261. [
  262. (
  263. "test_state.add_age",
  264. {"test_state": {"details": {"name": "Tommy", "age": 20}}},
  265. ),
  266. (
  267. "test_state.change_name",
  268. {"test_state": {"details": {"name": "Jenny", "age": 20}}},
  269. ),
  270. (
  271. "test_state.remove_last_detail",
  272. {"test_state": {"details": {"name": "Jenny"}}},
  273. ),
  274. ],
  275. id="update then __setitem__",
  276. ),
  277. pytest.param(
  278. [
  279. (
  280. "test_state.clear_details",
  281. {"test_state": {"details": {}}},
  282. ),
  283. (
  284. "test_state.add_age",
  285. {"test_state": {"details": {"age": 20}}},
  286. ),
  287. ],
  288. id="delitem then update",
  289. ),
  290. pytest.param(
  291. [
  292. (
  293. "test_state.add_age",
  294. {"test_state": {"details": {"name": "Tommy", "age": 20}}},
  295. ),
  296. (
  297. "test_state.remove_name",
  298. {"test_state": {"details": {"age": 20}}},
  299. ),
  300. (
  301. "test_state.pop_out_age",
  302. {"test_state": {"details": {}}},
  303. ),
  304. ],
  305. id="add, remove, pop",
  306. ),
  307. pytest.param(
  308. [
  309. (
  310. "test_state.remove_home_address",
  311. {"test_state": {"address": [{}, {"work": "work address"}]}},
  312. ),
  313. (
  314. "test_state.add_street_to_home_address",
  315. {
  316. "test_state": {
  317. "address": [
  318. {"street": "street address"},
  319. {"work": "work address"},
  320. ]
  321. }
  322. },
  323. ),
  324. ],
  325. id="dict in list",
  326. ),
  327. pytest.param(
  328. [
  329. (
  330. "test_state.change_friend_name",
  331. {
  332. "test_state": {
  333. "friend_in_nested_dict": {
  334. "name": "Nikhil",
  335. "friend": {"name": "Tommy"},
  336. }
  337. }
  338. },
  339. ),
  340. (
  341. "test_state.add_friend_age",
  342. {
  343. "test_state": {
  344. "friend_in_nested_dict": {
  345. "name": "Nikhil",
  346. "friend": {"name": "Tommy", "age": 30},
  347. }
  348. }
  349. },
  350. ),
  351. (
  352. "test_state.remove_friend",
  353. {"test_state": {"friend_in_nested_dict": {"name": "Nikhil"}}},
  354. ),
  355. ],
  356. id="nested dict",
  357. ),
  358. ],
  359. )
  360. async def test_dict_mutation_detection__plain_list(
  361. event_tuples: List[Tuple[str, List[str]]], dict_mutation_state: State
  362. ):
  363. """Test dict mutation detection
  364. when reassignment is not explicitly included in the logic.
  365. Args:
  366. event_tuples: From parametrization.
  367. dict_mutation_state: A state with dict mutation features.
  368. """
  369. for event_name, expected_delta in event_tuples:
  370. result = await dict_mutation_state._process(
  371. Event(
  372. token="fake-token",
  373. name=event_name,
  374. router_data={"pathname": "/", "query": {}},
  375. payload={},
  376. )
  377. )
  378. assert result.delta == expected_delta
  379. @pytest.mark.asyncio
  380. @pytest.mark.parametrize(
  381. "fixture, expected",
  382. [
  383. (
  384. "upload_state",
  385. {"file_upload_state": {"img_list": ["image1.jpg", "image2.jpg"]}},
  386. ),
  387. (
  388. "upload_sub_state",
  389. {
  390. "file_state.file_upload_state": {
  391. "img_list": ["image1.jpg", "image2.jpg"]
  392. }
  393. },
  394. ),
  395. (
  396. "upload_grand_sub_state",
  397. {
  398. "base_file_state.file_sub_state.file_upload_state": {
  399. "img_list": ["image1.jpg", "image2.jpg"]
  400. }
  401. },
  402. ),
  403. ],
  404. )
  405. async def test_upload_file(fixture, request, expected):
  406. """Test that file upload works correctly.
  407. Args:
  408. fixture: The state.
  409. request: Fixture request.
  410. expected: Expected delta
  411. """
  412. data = b"This is binary data"
  413. # Create a binary IO object and write data to it
  414. bio = io.BytesIO()
  415. bio.write(data)
  416. app = App(state=request.getfixturevalue(fixture))
  417. file1 = UploadFile(
  418. filename="token:file_upload_state.multi_handle_upload:True:image1.jpg",
  419. file=bio,
  420. content_type="image/jpeg",
  421. )
  422. file2 = UploadFile(
  423. filename="token:file_upload_state.multi_handle_upload:True:image2.jpg",
  424. file=bio,
  425. content_type="image/jpeg",
  426. )
  427. fn = upload(app)
  428. result = await fn([file1, file2]) # type: ignore
  429. assert isinstance(result, StateUpdate)
  430. assert result.delta == expected
  431. @pytest.mark.asyncio
  432. @pytest.mark.parametrize(
  433. "fixture", ["upload_state", "upload_sub_state", "upload_grand_sub_state"]
  434. )
  435. async def test_upload_file_without_annotation(fixture, request):
  436. """Test that an error is thrown when there's no param annotated with pc.UploadFile or List[UploadFile].
  437. Args:
  438. fixture: The state.
  439. request: Fixture request.
  440. """
  441. data = b"This is binary data"
  442. # Create a binary IO object and write data to it
  443. bio = io.BytesIO()
  444. bio.write(data)
  445. app = App(state=request.getfixturevalue(fixture))
  446. file1 = UploadFile(
  447. filename="token:file_upload_state.handle_upload2:True:image1.jpg",
  448. file=bio,
  449. content_type="image/jpeg",
  450. )
  451. file2 = UploadFile(
  452. filename="token:file_upload_state.handle_upload2:True:image2.jpg",
  453. file=bio,
  454. content_type="image/jpeg",
  455. )
  456. fn = upload(app)
  457. with pytest.raises(ValueError) as err:
  458. await fn([file1, file2])
  459. assert (
  460. err.value.args[0]
  461. == "`file_upload_state.handle_upload2` handler should have a parameter annotated as List[pc.UploadFile]"
  462. )