test_upload.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Integration tests for file upload."""
  2. from __future__ import annotations
  3. import time
  4. from typing import Generator
  5. import pytest
  6. from selenium.webdriver.common.by import By
  7. from reflex.testing import AppHarness
  8. def UploadFile():
  9. """App for testing dynamic routes."""
  10. import reflex as rx
  11. class UploadState(rx.State):
  12. _file_data: dict[str, str] = {}
  13. async def handle_upload(self, files: list[rx.UploadFile]):
  14. for file in files:
  15. upload_data = await file.read()
  16. self._file_data[file.filename or ""] = upload_data.decode("utf-8")
  17. @rx.var
  18. def token(self) -> str:
  19. return self.get_token()
  20. def index():
  21. return rx.vstack(
  22. rx.input(value=UploadState.token, is_read_only=True, id="token"),
  23. rx.upload(
  24. rx.vstack(
  25. rx.button("Select File"),
  26. rx.text("Drag and drop files here or click to select files"),
  27. ),
  28. ),
  29. rx.button(
  30. "Upload",
  31. on_click=lambda: UploadState.handle_upload(rx.upload_files()), # type: ignore
  32. id="upload_button",
  33. ),
  34. rx.box(
  35. rx.foreach(
  36. rx.selected_files,
  37. lambda f: rx.text(f),
  38. ),
  39. id="selected_files",
  40. ),
  41. rx.button(
  42. "Clear",
  43. on_click=rx.clear_selected_files,
  44. id="clear_button",
  45. ),
  46. )
  47. app = rx.App(state=UploadState)
  48. app.add_page(index)
  49. app.compile()
  50. @pytest.fixture(scope="session")
  51. def upload_file(tmp_path_factory) -> Generator[AppHarness, None, None]:
  52. """Start UploadFile app at tmp_path via AppHarness.
  53. Args:
  54. tmp_path_factory: pytest tmp_path_factory fixture
  55. Yields:
  56. running AppHarness instance
  57. """
  58. with AppHarness.create(
  59. root=tmp_path_factory.mktemp("upload_file"),
  60. app_source=UploadFile, # type: ignore
  61. ) as harness:
  62. yield harness
  63. @pytest.fixture
  64. def driver(upload_file: AppHarness):
  65. """Get an instance of the browser open to the upload_file app.
  66. Args:
  67. upload_file: harness for DynamicRoute app
  68. Yields:
  69. WebDriver instance.
  70. """
  71. assert upload_file.app_instance is not None, "app is not running"
  72. driver = upload_file.frontend()
  73. try:
  74. yield driver
  75. finally:
  76. driver.quit()
  77. @pytest.mark.asyncio
  78. async def test_upload_file(tmp_path, upload_file: AppHarness, driver):
  79. """Submit a file upload and check that it arrived on the backend.
  80. Args:
  81. tmp_path: pytest tmp_path fixture
  82. upload_file: harness for UploadFile app.
  83. driver: WebDriver instance.
  84. """
  85. assert upload_file.app_instance is not None
  86. token_input = driver.find_element(By.ID, "token")
  87. assert token_input
  88. # wait for the backend connection to send the token
  89. token = upload_file.poll_for_value(token_input)
  90. assert token is not None
  91. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  92. assert upload_box
  93. upload_button = driver.find_element(By.ID, "upload_button")
  94. assert upload_button
  95. exp_name = "test.txt"
  96. exp_contents = "test file contents!"
  97. target_file = tmp_path / exp_name
  98. target_file.write_text(exp_contents)
  99. upload_box.send_keys(str(target_file))
  100. upload_button.click()
  101. # look up the backend state and assert on uploaded contents
  102. async def get_file_data():
  103. return (await upload_file.get_state(token))._file_data
  104. file_data = await AppHarness._poll_for_async(get_file_data)
  105. assert isinstance(file_data, dict)
  106. assert file_data[exp_name] == exp_contents
  107. # check that the selected files are displayed
  108. selected_files = driver.find_element(By.ID, "selected_files")
  109. assert selected_files.text == exp_name
  110. @pytest.mark.asyncio
  111. async def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
  112. """Submit several file uploads and check that they arrived on the backend.
  113. Args:
  114. tmp_path: pytest tmp_path fixture
  115. upload_file: harness for UploadFile app.
  116. driver: WebDriver instance.
  117. """
  118. assert upload_file.app_instance is not None
  119. token_input = driver.find_element(By.ID, "token")
  120. assert token_input
  121. # wait for the backend connection to send the token
  122. token = upload_file.poll_for_value(token_input)
  123. assert token is not None
  124. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  125. assert upload_box
  126. upload_button = driver.find_element(By.ID, "upload_button")
  127. assert upload_button
  128. exp_files = {
  129. "test1.txt": "test file contents!",
  130. "test2.txt": "this is test file number 2!",
  131. "reflex.txt": "reflex is awesome!",
  132. }
  133. for exp_name, exp_contents in exp_files.items():
  134. target_file = tmp_path / exp_name
  135. target_file.write_text(exp_contents)
  136. upload_box.send_keys(str(target_file))
  137. time.sleep(0.2)
  138. # check that the selected files are displayed
  139. selected_files = driver.find_element(By.ID, "selected_files")
  140. assert selected_files.text == "\n".join(exp_files)
  141. # do the upload
  142. upload_button.click()
  143. # look up the backend state and assert on uploaded contents
  144. async def get_file_data():
  145. return (await upload_file.get_state(token))._file_data
  146. file_data = await AppHarness._poll_for_async(get_file_data)
  147. assert isinstance(file_data, dict)
  148. for exp_name, exp_contents in exp_files.items():
  149. assert file_data[exp_name] == exp_contents
  150. def test_clear_files(tmp_path, upload_file: AppHarness, driver):
  151. """Select then clear several file uploads and check that they are cleared.
  152. Args:
  153. tmp_path: pytest tmp_path fixture
  154. upload_file: harness for UploadFile app.
  155. driver: WebDriver instance.
  156. """
  157. assert upload_file.app_instance is not None
  158. token_input = driver.find_element(By.ID, "token")
  159. assert token_input
  160. # wait for the backend connection to send the token
  161. token = upload_file.poll_for_value(token_input)
  162. assert token is not None
  163. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  164. assert upload_box
  165. upload_button = driver.find_element(By.ID, "upload_button")
  166. assert upload_button
  167. exp_files = {
  168. "test1.txt": "test file contents!",
  169. "test2.txt": "this is test file number 2!",
  170. "reflex.txt": "reflex is awesome!",
  171. }
  172. for exp_name, exp_contents in exp_files.items():
  173. target_file = tmp_path / exp_name
  174. target_file.write_text(exp_contents)
  175. upload_box.send_keys(str(target_file))
  176. time.sleep(0.2)
  177. # check that the selected files are displayed
  178. selected_files = driver.find_element(By.ID, "selected_files")
  179. assert selected_files.text == "\n".join(exp_files)
  180. clear_button = driver.find_element(By.ID, "clear_button")
  181. assert clear_button
  182. clear_button.click()
  183. # check that the selected files are cleared
  184. selected_files = driver.find_element(By.ID, "selected_files")
  185. assert selected_files.text == ""