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