test_upload.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. """Integration tests for file upload."""
  2. from __future__ import annotations
  3. import asyncio
  4. import time
  5. from pathlib import Path
  6. from typing import Generator
  7. from urllib.parse import urlsplit
  8. import pytest
  9. from selenium.webdriver.common.by import By
  10. from reflex.constants.event import Endpoint
  11. from reflex.testing import AppHarness, WebDriver
  12. from .utils import poll_for_navigation
  13. def UploadFile():
  14. """App for testing dynamic routes."""
  15. import reflex as rx
  16. LARGE_DATA = "DUMMY" * 1024 * 512
  17. class UploadState(rx.State):
  18. _file_data: dict[str, str] = {}
  19. event_order: rx.Field[list[str]] = rx.field([])
  20. progress_dicts: list[dict] = []
  21. disabled: bool = False
  22. large_data: str = ""
  23. async def handle_upload(self, files: list[rx.UploadFile]):
  24. for file in files:
  25. upload_data = await file.read()
  26. self._file_data[file.filename or ""] = upload_data.decode("utf-8")
  27. async def handle_upload_secondary(self, files: list[rx.UploadFile]):
  28. for file in files:
  29. upload_data = await file.read()
  30. self._file_data[file.filename or ""] = upload_data.decode("utf-8")
  31. self.large_data = LARGE_DATA
  32. yield UploadState.chain_event
  33. def upload_progress(self, progress):
  34. assert progress
  35. self.event_order.append("upload_progress")
  36. self.progress_dicts.append(progress)
  37. def chain_event(self):
  38. assert self.large_data == LARGE_DATA
  39. self.large_data = ""
  40. self.event_order.append("chain_event")
  41. @rx.event
  42. async def handle_upload_tertiary(self, files: list[rx.UploadFile]):
  43. for file in files:
  44. (rx.get_upload_dir() / (file.filename or "INVALID")).write_bytes(
  45. await file.read()
  46. )
  47. @rx.event
  48. def do_download(self):
  49. return rx.download(rx.get_upload_url("test.txt"))
  50. def index():
  51. return rx.vstack(
  52. rx.input(
  53. value=UploadState.router.session.client_token,
  54. read_only=True,
  55. id="token",
  56. ),
  57. rx.heading("Default Upload"),
  58. rx.upload.root(
  59. rx.vstack(
  60. rx.button("Select File"),
  61. rx.text("Drag and drop files here or click to select files"),
  62. ),
  63. disabled=UploadState.disabled,
  64. ),
  65. rx.button(
  66. "Upload",
  67. on_click=lambda: UploadState.handle_upload(rx.upload_files()), # pyright: ignore [reportCallIssue]
  68. id="upload_button",
  69. ),
  70. rx.box(
  71. rx.foreach(
  72. rx.selected_files(),
  73. lambda f: rx.text(f, as_="p"),
  74. ),
  75. id="selected_files",
  76. ),
  77. rx.button(
  78. "Clear",
  79. on_click=rx.clear_selected_files,
  80. id="clear_button",
  81. ),
  82. rx.heading("Secondary Upload"),
  83. rx.upload.root(
  84. rx.vstack(
  85. rx.button("Select File"),
  86. rx.text("Drag and drop files here or click to select files"),
  87. ),
  88. id="secondary",
  89. ),
  90. rx.button(
  91. "Upload",
  92. on_click=UploadState.handle_upload_secondary( # pyright: ignore [reportCallIssue]
  93. rx.upload_files(
  94. upload_id="secondary",
  95. on_upload_progress=UploadState.upload_progress,
  96. ),
  97. ),
  98. id="upload_button_secondary",
  99. ),
  100. rx.box(
  101. rx.foreach(
  102. rx.selected_files("secondary"),
  103. lambda f: rx.text(f, as_="p"),
  104. ),
  105. id="selected_files_secondary",
  106. ),
  107. rx.button(
  108. "Clear",
  109. on_click=rx.clear_selected_files("secondary"),
  110. id="clear_button_secondary",
  111. ),
  112. rx.vstack(
  113. rx.foreach(
  114. UploadState.progress_dicts,
  115. lambda d: rx.text(d.to_string()),
  116. )
  117. ),
  118. rx.button(
  119. "Cancel",
  120. on_click=rx.cancel_upload("secondary"),
  121. id="cancel_button_secondary",
  122. ),
  123. rx.heading("Tertiary Upload/Download"),
  124. rx.upload.root(
  125. rx.vstack(
  126. rx.button("Select File"),
  127. rx.text("Drag and drop files here or click to select files"),
  128. ),
  129. id="tertiary",
  130. ),
  131. rx.button(
  132. "Upload",
  133. on_click=UploadState.handle_upload_tertiary(
  134. rx.upload_files( # pyright: ignore [reportArgumentType]
  135. upload_id="tertiary",
  136. ),
  137. ),
  138. id="upload_button_tertiary",
  139. ),
  140. rx.button(
  141. "Download - Frontend",
  142. on_click=rx.download(rx.get_upload_url("test.txt")),
  143. id="download-frontend",
  144. ),
  145. rx.button(
  146. "Download - Backend",
  147. on_click=UploadState.do_download,
  148. id="download-backend",
  149. ),
  150. rx.text(UploadState.event_order.to_string(), id="event-order"),
  151. )
  152. app = rx.App()
  153. app.add_page(index)
  154. @pytest.fixture(scope="module")
  155. def upload_file(tmp_path_factory) -> Generator[AppHarness, None, None]:
  156. """Start UploadFile app at tmp_path via AppHarness.
  157. Args:
  158. tmp_path_factory: pytest tmp_path_factory fixture
  159. Yields:
  160. running AppHarness instance
  161. """
  162. with AppHarness.create(
  163. root=tmp_path_factory.mktemp("upload_file"),
  164. app_source=UploadFile,
  165. ) as harness:
  166. yield harness
  167. @pytest.fixture
  168. def driver(upload_file: AppHarness):
  169. """Get an instance of the browser open to the upload_file app.
  170. Args:
  171. upload_file: harness for DynamicRoute app
  172. Yields:
  173. WebDriver instance.
  174. """
  175. assert upload_file.app_instance is not None, "app is not running"
  176. driver = upload_file.frontend()
  177. try:
  178. yield driver
  179. finally:
  180. driver.quit()
  181. def poll_for_token(driver: WebDriver, upload_file: AppHarness) -> str:
  182. """Poll for the token input to be populated.
  183. Args:
  184. driver: WebDriver instance.
  185. upload_file: harness for UploadFile app.
  186. Returns:
  187. token value
  188. """
  189. token_input = driver.find_element(By.ID, "token")
  190. assert token_input
  191. # wait for the backend connection to send the token
  192. token = upload_file.poll_for_value(token_input)
  193. assert token is not None
  194. return token
  195. @pytest.mark.parametrize("secondary", [False, True])
  196. @pytest.mark.asyncio
  197. async def test_upload_file(
  198. tmp_path, upload_file: AppHarness, driver: WebDriver, secondary: bool
  199. ):
  200. """Submit a file upload and check that it arrived on the backend.
  201. Args:
  202. tmp_path: pytest tmp_path fixture
  203. upload_file: harness for UploadFile app.
  204. driver: WebDriver instance.
  205. secondary: whether to use the secondary upload form
  206. """
  207. assert upload_file.app_instance is not None
  208. token = poll_for_token(driver, upload_file)
  209. full_state_name = upload_file.get_full_state_name(["_upload_state"])
  210. state_name = upload_file.get_state_name("_upload_state")
  211. substate_token = f"{token}_{full_state_name}"
  212. suffix = "_secondary" if secondary else ""
  213. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[
  214. 1 if secondary else 0
  215. ]
  216. assert upload_box
  217. upload_button = driver.find_element(By.ID, f"upload_button{suffix}")
  218. assert upload_button
  219. exp_name = "test.txt"
  220. exp_contents = "test file contents!"
  221. target_file = tmp_path / exp_name
  222. target_file.write_text(exp_contents)
  223. upload_box.send_keys(str(target_file))
  224. upload_button.click()
  225. # check that the selected files are displayed
  226. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  227. assert Path(selected_files.text).name == Path(exp_name).name
  228. if secondary:
  229. event_order_displayed = driver.find_element(By.ID, "event-order")
  230. AppHarness._poll_for(lambda: "chain_event" in event_order_displayed.text)
  231. state = await upload_file.get_state(substate_token)
  232. # only the secondary form tracks progress and chain events
  233. assert state.substates[state_name].event_order.count("upload_progress") == 1
  234. assert state.substates[state_name].event_order.count("chain_event") == 1
  235. # look up the backend state and assert on uploaded contents
  236. async def get_file_data():
  237. return (
  238. (await upload_file.get_state(substate_token))
  239. .substates[state_name]
  240. ._file_data
  241. )
  242. file_data = await AppHarness._poll_for_async(get_file_data)
  243. assert isinstance(file_data, dict)
  244. normalized_file_data = {Path(k).name: v for k, v in file_data.items()}
  245. assert normalized_file_data[Path(exp_name).name] == exp_contents
  246. @pytest.mark.asyncio
  247. async def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
  248. """Submit several file uploads and check that they arrived on the backend.
  249. Args:
  250. tmp_path: pytest tmp_path fixture
  251. upload_file: harness for UploadFile app.
  252. driver: WebDriver instance.
  253. """
  254. assert upload_file.app_instance is not None
  255. token = poll_for_token(driver, upload_file)
  256. full_state_name = upload_file.get_full_state_name(["_upload_state"])
  257. state_name = upload_file.get_state_name("_upload_state")
  258. substate_token = f"{token}_{full_state_name}"
  259. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  260. assert upload_box
  261. upload_button = driver.find_element(By.ID, "upload_button")
  262. assert upload_button
  263. exp_files = {
  264. "test1.txt": "test file contents!",
  265. "test2.txt": "this is test file number 2!",
  266. "reflex.txt": "reflex is awesome!",
  267. }
  268. for exp_name, exp_contents in exp_files.items():
  269. target_file = tmp_path / exp_name
  270. target_file.write_text(exp_contents)
  271. upload_box.send_keys(str(target_file))
  272. time.sleep(0.2)
  273. # check that the selected files are displayed
  274. selected_files = driver.find_element(By.ID, "selected_files")
  275. assert [Path(name).name for name in selected_files.text.split("\n")] == [
  276. Path(name).name for name in exp_files
  277. ]
  278. # do the upload
  279. upload_button.click()
  280. # look up the backend state and assert on uploaded contents
  281. async def get_file_data():
  282. return (
  283. (await upload_file.get_state(substate_token))
  284. .substates[state_name]
  285. ._file_data
  286. )
  287. file_data = await AppHarness._poll_for_async(get_file_data)
  288. assert isinstance(file_data, dict)
  289. normalized_file_data = {Path(k).name: v for k, v in file_data.items()}
  290. for exp_name, exp_contents in exp_files.items():
  291. assert normalized_file_data[Path(exp_name).name] == exp_contents
  292. @pytest.mark.parametrize("secondary", [False, True])
  293. def test_clear_files(
  294. tmp_path, upload_file: AppHarness, driver: WebDriver, secondary: bool
  295. ):
  296. """Select then clear several file uploads and check that they are cleared.
  297. Args:
  298. tmp_path: pytest tmp_path fixture
  299. upload_file: harness for UploadFile app.
  300. driver: WebDriver instance.
  301. secondary: whether to use the secondary upload form.
  302. """
  303. assert upload_file.app_instance is not None
  304. poll_for_token(driver, upload_file)
  305. suffix = "_secondary" if secondary else ""
  306. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[
  307. 1 if secondary else 0
  308. ]
  309. assert upload_box
  310. upload_button = driver.find_element(By.ID, f"upload_button{suffix}")
  311. assert upload_button
  312. exp_files = {
  313. "test1.txt": "test file contents!",
  314. "test2.txt": "this is test file number 2!",
  315. "reflex.txt": "reflex is awesome!",
  316. }
  317. for exp_name, exp_contents in exp_files.items():
  318. target_file = tmp_path / exp_name
  319. target_file.write_text(exp_contents)
  320. upload_box.send_keys(str(target_file))
  321. time.sleep(0.2)
  322. # check that the selected files are displayed
  323. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  324. assert [Path(name).name for name in selected_files.text.split("\n")] == [
  325. Path(name).name for name in exp_files
  326. ]
  327. clear_button = driver.find_element(By.ID, f"clear_button{suffix}")
  328. assert clear_button
  329. clear_button.click()
  330. # check that the selected files are cleared
  331. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  332. assert selected_files.text == ""
  333. # TODO: drag and drop directory
  334. # https://gist.github.com/florentbr/349b1ab024ca9f3de56e6bf8af2ac69e
  335. @pytest.mark.asyncio
  336. async def test_cancel_upload(tmp_path, upload_file: AppHarness, driver: WebDriver):
  337. """Submit a large file upload and cancel it.
  338. Args:
  339. tmp_path: pytest tmp_path fixture
  340. upload_file: harness for UploadFile app.
  341. driver: WebDriver instance.
  342. """
  343. assert upload_file.app_instance is not None
  344. token = poll_for_token(driver, upload_file)
  345. state_name = upload_file.get_state_name("_upload_state")
  346. state_full_name = upload_file.get_full_state_name(["_upload_state"])
  347. substate_token = f"{token}_{state_full_name}"
  348. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[1]
  349. upload_button = driver.find_element(By.ID, "upload_button_secondary")
  350. cancel_button = driver.find_element(By.ID, "cancel_button_secondary")
  351. exp_name = "large.txt"
  352. target_file = tmp_path / exp_name
  353. with target_file.open("wb") as f:
  354. f.seek(1024 * 1024 * 256)
  355. f.write(b"0")
  356. upload_box.send_keys(str(target_file))
  357. upload_button.click()
  358. await asyncio.sleep(0.3)
  359. cancel_button.click()
  360. # Wait a bit for the upload to get cancelled.
  361. await asyncio.sleep(0.5)
  362. # Get interim progress dicts saved in the on_upload_progress handler.
  363. async def _progress_dicts():
  364. state = await upload_file.get_state(substate_token)
  365. return state.substates[state_name].progress_dicts
  366. # We should have _some_ progress
  367. assert await AppHarness._poll_for_async(_progress_dicts)
  368. # But there should never be a final progress record for a cancelled upload.
  369. for p in await _progress_dicts():
  370. assert p["progress"] != 1
  371. state = await upload_file.get_state(substate_token)
  372. file_data = state.substates[state_name]._file_data
  373. assert isinstance(file_data, dict)
  374. normalized_file_data = {Path(k).name: v for k, v in file_data.items()}
  375. assert Path(exp_name).name not in normalized_file_data
  376. target_file.unlink()
  377. @pytest.mark.asyncio
  378. async def test_upload_download_file(
  379. tmp_path,
  380. upload_file: AppHarness,
  381. driver: WebDriver,
  382. ):
  383. """Submit a file upload and then fetch it with rx.download.
  384. This checks the special case `getBackendURL` logic in the _download event
  385. handler in state.js.
  386. Args:
  387. tmp_path: pytest tmp_path fixture
  388. upload_file: harness for UploadFile app.
  389. driver: WebDriver instance.
  390. """
  391. assert upload_file.app_instance is not None
  392. poll_for_token(driver, upload_file)
  393. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[2]
  394. assert upload_box
  395. upload_button = driver.find_element(By.ID, "upload_button_tertiary")
  396. assert upload_button
  397. exp_name = "test.txt"
  398. exp_contents = "test file contents!"
  399. target_file = tmp_path / exp_name
  400. target_file.write_text(exp_contents)
  401. upload_box.send_keys(str(target_file))
  402. upload_button.click()
  403. # Download via event embedded in frontend code.
  404. download_frontend = driver.find_element(By.ID, "download-frontend")
  405. with poll_for_navigation(driver):
  406. download_frontend.click()
  407. assert urlsplit(driver.current_url).path == f"/{Endpoint.UPLOAD.value}/test.txt"
  408. assert driver.find_element(by=By.TAG_NAME, value="body").text == exp_contents
  409. # Go back and wait for the app to reload.
  410. with poll_for_navigation(driver):
  411. driver.back()
  412. poll_for_token(driver, upload_file)
  413. # Download via backend event handler.
  414. download_backend = driver.find_element(By.ID, "download-backend")
  415. with poll_for_navigation(driver):
  416. download_backend.click()
  417. assert urlsplit(driver.current_url).path == f"/{Endpoint.UPLOAD.value}/test.txt"
  418. assert driver.find_element(by=By.TAG_NAME, value="body").text == exp_contents