test_upload.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. """Integration tests for file upload."""
  2. from __future__ import annotations
  3. import asyncio
  4. import time
  5. from typing import Generator
  6. import pytest
  7. from selenium.webdriver.common.by import By
  8. from reflex.testing import AppHarness, WebDriver
  9. def UploadFile():
  10. """App for testing dynamic routes."""
  11. import reflex as rx
  12. class UploadState(rx.State):
  13. _file_data: dict[str, str] = {}
  14. event_order: list[str] = []
  15. progress_dicts: list[dict] = []
  16. async def handle_upload(self, files: list[rx.UploadFile]):
  17. for file in files:
  18. upload_data = await file.read()
  19. self._file_data[file.filename or ""] = upload_data.decode("utf-8")
  20. async def handle_upload_secondary(self, files: list[rx.UploadFile]):
  21. for file in files:
  22. upload_data = await file.read()
  23. self._file_data[file.filename or ""] = upload_data.decode("utf-8")
  24. yield UploadState.chain_event
  25. def upload_progress(self, progress):
  26. assert progress
  27. self.event_order.append("upload_progress")
  28. self.progress_dicts.append(progress)
  29. def chain_event(self):
  30. self.event_order.append("chain_event")
  31. def index():
  32. return rx.vstack(
  33. rx.input(
  34. value=UploadState.router.session.client_token,
  35. is_read_only=True,
  36. id="token",
  37. ),
  38. rx.heading("Default Upload"),
  39. rx.upload(
  40. rx.vstack(
  41. rx.button("Select File"),
  42. rx.text("Drag and drop files here or click to select files"),
  43. ),
  44. ),
  45. rx.button(
  46. "Upload",
  47. on_click=lambda: UploadState.handle_upload(rx.upload_files()), # type: ignore
  48. id="upload_button",
  49. ),
  50. rx.box(
  51. rx.foreach(
  52. rx.selected_files,
  53. lambda f: rx.text(f),
  54. ),
  55. id="selected_files",
  56. ),
  57. rx.button(
  58. "Clear",
  59. on_click=rx.clear_selected_files,
  60. id="clear_button",
  61. ),
  62. rx.heading("Secondary Upload"),
  63. rx.upload(
  64. rx.vstack(
  65. rx.button("Select File"),
  66. rx.text("Drag and drop files here or click to select files"),
  67. ),
  68. id="secondary",
  69. ),
  70. rx.button(
  71. "Upload",
  72. on_click=UploadState.handle_upload_secondary( # type: ignore
  73. rx.upload_files(
  74. upload_id="secondary",
  75. on_upload_progress=UploadState.upload_progress,
  76. ),
  77. ),
  78. id="upload_button_secondary",
  79. ),
  80. rx.box(
  81. rx.foreach(
  82. rx.selected_files("secondary"),
  83. lambda f: rx.text(f),
  84. ),
  85. id="selected_files_secondary",
  86. ),
  87. rx.button(
  88. "Clear",
  89. on_click=rx.clear_selected_files("secondary"),
  90. id="clear_button_secondary",
  91. ),
  92. rx.vstack(
  93. rx.foreach(
  94. UploadState.progress_dicts, # type: ignore
  95. lambda d: rx.text(d.to_string()),
  96. )
  97. ),
  98. rx.button(
  99. "Cancel",
  100. on_click=rx.cancel_upload("secondary"),
  101. id="cancel_button_secondary",
  102. ),
  103. )
  104. app = rx.App(state=rx.State)
  105. app.add_page(index)
  106. app.compile()
  107. @pytest.fixture(scope="session")
  108. def upload_file(tmp_path_factory) -> Generator[AppHarness, None, None]:
  109. """Start UploadFile app at tmp_path via AppHarness.
  110. Args:
  111. tmp_path_factory: pytest tmp_path_factory fixture
  112. Yields:
  113. running AppHarness instance
  114. """
  115. with AppHarness.create(
  116. root=tmp_path_factory.mktemp("upload_file"),
  117. app_source=UploadFile, # type: ignore
  118. ) as harness:
  119. yield harness
  120. @pytest.fixture
  121. def driver(upload_file: AppHarness):
  122. """Get an instance of the browser open to the upload_file app.
  123. Args:
  124. upload_file: harness for DynamicRoute app
  125. Yields:
  126. WebDriver instance.
  127. """
  128. assert upload_file.app_instance is not None, "app is not running"
  129. driver = upload_file.frontend()
  130. try:
  131. yield driver
  132. finally:
  133. driver.quit()
  134. @pytest.mark.parametrize("secondary", [False, True])
  135. @pytest.mark.asyncio
  136. async def test_upload_file(
  137. tmp_path, upload_file: AppHarness, driver: WebDriver, secondary: bool
  138. ):
  139. """Submit a file upload and check that it arrived on the backend.
  140. Args:
  141. tmp_path: pytest tmp_path fixture
  142. upload_file: harness for UploadFile app.
  143. driver: WebDriver instance.
  144. secondary: whether to use the secondary upload form
  145. """
  146. assert upload_file.app_instance is not None
  147. token_input = driver.find_element(By.ID, "token")
  148. assert token_input
  149. # wait for the backend connection to send the token
  150. token = upload_file.poll_for_value(token_input)
  151. assert token is not None
  152. suffix = "_secondary" if secondary else ""
  153. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[
  154. 1 if secondary else 0
  155. ]
  156. assert upload_box
  157. upload_button = driver.find_element(By.ID, f"upload_button{suffix}")
  158. assert upload_button
  159. exp_name = "test.txt"
  160. exp_contents = "test file contents!"
  161. target_file = tmp_path / exp_name
  162. target_file.write_text(exp_contents)
  163. upload_box.send_keys(str(target_file))
  164. upload_button.click()
  165. # look up the backend state and assert on uploaded contents
  166. async def get_file_data():
  167. return (await upload_file.get_state(token)).substates["upload_state"]._file_data
  168. file_data = await AppHarness._poll_for_async(get_file_data)
  169. assert isinstance(file_data, dict)
  170. assert file_data[exp_name] == exp_contents
  171. # check that the selected files are displayed
  172. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  173. assert selected_files.text == exp_name
  174. state = await upload_file.get_state(token)
  175. if secondary:
  176. # only the secondary form tracks progress and chain events
  177. assert state.substates["upload_state"].event_order.count("upload_progress") == 1
  178. assert state.substates["upload_state"].event_order.count("chain_event") == 1
  179. @pytest.mark.asyncio
  180. async def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
  181. """Submit several file uploads and check that they arrived on the backend.
  182. Args:
  183. tmp_path: pytest tmp_path fixture
  184. upload_file: harness for UploadFile app.
  185. driver: WebDriver instance.
  186. """
  187. assert upload_file.app_instance is not None
  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. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  194. assert upload_box
  195. upload_button = driver.find_element(By.ID, "upload_button")
  196. assert upload_button
  197. exp_files = {
  198. "test1.txt": "test file contents!",
  199. "test2.txt": "this is test file number 2!",
  200. "reflex.txt": "reflex is awesome!",
  201. }
  202. for exp_name, exp_contents in exp_files.items():
  203. target_file = tmp_path / exp_name
  204. target_file.write_text(exp_contents)
  205. upload_box.send_keys(str(target_file))
  206. time.sleep(0.2)
  207. # check that the selected files are displayed
  208. selected_files = driver.find_element(By.ID, "selected_files")
  209. assert selected_files.text == "\n".join(exp_files)
  210. # do the upload
  211. upload_button.click()
  212. # look up the backend state and assert on uploaded contents
  213. async def get_file_data():
  214. return (await upload_file.get_state(token)).substates["upload_state"]._file_data
  215. file_data = await AppHarness._poll_for_async(get_file_data)
  216. assert isinstance(file_data, dict)
  217. for exp_name, exp_contents in exp_files.items():
  218. assert file_data[exp_name] == exp_contents
  219. @pytest.mark.parametrize("secondary", [False, True])
  220. def test_clear_files(
  221. tmp_path, upload_file: AppHarness, driver: WebDriver, secondary: bool
  222. ):
  223. """Select then clear several file uploads and check that they are cleared.
  224. Args:
  225. tmp_path: pytest tmp_path fixture
  226. upload_file: harness for UploadFile app.
  227. driver: WebDriver instance.
  228. secondary: whether to use the secondary upload form.
  229. """
  230. assert upload_file.app_instance is not None
  231. token_input = driver.find_element(By.ID, "token")
  232. assert token_input
  233. # wait for the backend connection to send the token
  234. token = upload_file.poll_for_value(token_input)
  235. assert token is not None
  236. suffix = "_secondary" if secondary else ""
  237. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[
  238. 1 if secondary else 0
  239. ]
  240. assert upload_box
  241. upload_button = driver.find_element(By.ID, f"upload_button{suffix}")
  242. assert upload_button
  243. exp_files = {
  244. "test1.txt": "test file contents!",
  245. "test2.txt": "this is test file number 2!",
  246. "reflex.txt": "reflex is awesome!",
  247. }
  248. for exp_name, exp_contents in exp_files.items():
  249. target_file = tmp_path / exp_name
  250. target_file.write_text(exp_contents)
  251. upload_box.send_keys(str(target_file))
  252. time.sleep(0.2)
  253. # check that the selected files are displayed
  254. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  255. assert selected_files.text == "\n".join(exp_files)
  256. clear_button = driver.find_element(By.ID, f"clear_button{suffix}")
  257. assert clear_button
  258. clear_button.click()
  259. # check that the selected files are cleared
  260. selected_files = driver.find_element(By.ID, f"selected_files{suffix}")
  261. assert selected_files.text == ""
  262. # TODO: drag and drop directory
  263. # https://gist.github.com/florentbr/349b1ab024ca9f3de56e6bf8af2ac69e
  264. @pytest.mark.asyncio
  265. async def test_cancel_upload(tmp_path, upload_file: AppHarness, driver: WebDriver):
  266. """Submit a large file upload and cancel it.
  267. Args:
  268. tmp_path: pytest tmp_path fixture
  269. upload_file: harness for UploadFile app.
  270. driver: WebDriver instance.
  271. """
  272. assert upload_file.app_instance is not None
  273. token_input = driver.find_element(By.ID, "token")
  274. assert token_input
  275. # wait for the backend connection to send the token
  276. token = upload_file.poll_for_value(token_input)
  277. assert token is not None
  278. upload_box = driver.find_elements(By.XPATH, "//input[@type='file']")[1]
  279. upload_button = driver.find_element(By.ID, f"upload_button_secondary")
  280. cancel_button = driver.find_element(By.ID, f"cancel_button_secondary")
  281. exp_name = "large.txt"
  282. target_file = tmp_path / exp_name
  283. with target_file.open("wb") as f:
  284. f.seek(1024 * 1024 * 256)
  285. f.write(b"0")
  286. upload_box.send_keys(str(target_file))
  287. upload_button.click()
  288. await asyncio.sleep(0.3)
  289. cancel_button.click()
  290. # look up the backend state and assert on progress
  291. state = await upload_file.get_state(token)
  292. assert state.substates["upload_state"].progress_dicts
  293. assert exp_name not in state.substates["upload_state"]._file_data
  294. target_file.unlink()