test_upload.py 5.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  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. )
  42. app = rx.App(state=UploadState)
  43. app.add_page(index)
  44. app.compile()
  45. @pytest.fixture(scope="session")
  46. def upload_file(tmp_path_factory) -> Generator[AppHarness, None, None]:
  47. """Start UploadFile app at tmp_path via AppHarness.
  48. Args:
  49. tmp_path_factory: pytest tmp_path_factory fixture
  50. Yields:
  51. running AppHarness instance
  52. """
  53. with AppHarness.create(
  54. root=tmp_path_factory.mktemp("upload_file"),
  55. app_source=UploadFile, # type: ignore
  56. ) as harness:
  57. yield harness
  58. @pytest.fixture
  59. def driver(upload_file: AppHarness):
  60. """Get an instance of the browser open to the upload_file app.
  61. Args:
  62. upload_file: harness for DynamicRoute app
  63. Yields:
  64. WebDriver instance.
  65. """
  66. assert upload_file.app_instance is not None, "app is not running"
  67. driver = upload_file.frontend()
  68. try:
  69. assert upload_file.poll_for_clients()
  70. yield driver
  71. finally:
  72. driver.quit()
  73. def test_upload_file(tmp_path, upload_file: AppHarness, driver):
  74. """Submit a file upload and check that it arrived on the backend.
  75. Args:
  76. tmp_path: pytest tmp_path fixture
  77. upload_file: harness for UploadFile app.
  78. driver: WebDriver instance.
  79. """
  80. assert upload_file.app_instance is not None
  81. token_input = driver.find_element(By.ID, "token")
  82. assert token_input
  83. # wait for the backend connection to send the token
  84. token = upload_file.poll_for_value(token_input)
  85. assert token is not None
  86. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  87. assert upload_box
  88. upload_button = driver.find_element(By.ID, "upload_button")
  89. assert upload_button
  90. exp_name = "test.txt"
  91. exp_contents = "test file contents!"
  92. target_file = tmp_path / exp_name
  93. target_file.write_text(exp_contents)
  94. upload_box.send_keys(str(target_file))
  95. upload_button.click()
  96. # look up the backend state and assert on uploaded contents
  97. backend_state = upload_file.app_instance.state_manager.states[token]
  98. time.sleep(0.5)
  99. assert backend_state._file_data[exp_name] == exp_contents
  100. # check that the selected files are displayed
  101. selected_files = driver.find_element(By.ID, "selected_files")
  102. assert selected_files.text == exp_name
  103. def test_upload_file_multiple(tmp_path, upload_file: AppHarness, driver):
  104. """Submit several file uploads and check that they arrived on the backend.
  105. Args:
  106. tmp_path: pytest tmp_path fixture
  107. upload_file: harness for UploadFile app.
  108. driver: WebDriver instance.
  109. """
  110. assert upload_file.app_instance is not None
  111. token_input = driver.find_element(By.ID, "token")
  112. assert token_input
  113. # wait for the backend connection to send the token
  114. token = upload_file.poll_for_value(token_input)
  115. assert token is not None
  116. upload_box = driver.find_element(By.XPATH, "//input[@type='file']")
  117. assert upload_box
  118. upload_button = driver.find_element(By.ID, "upload_button")
  119. assert upload_button
  120. exp_files = {
  121. "test1.txt": "test file contents!",
  122. "test2.txt": "this is test file number 2!",
  123. "reflex.txt": "reflex is awesome!",
  124. }
  125. for exp_name, exp_contents in exp_files.items():
  126. target_file = tmp_path / exp_name
  127. target_file.write_text(exp_contents)
  128. upload_box.send_keys(str(target_file))
  129. time.sleep(0.2)
  130. # check that the selected files are displayed
  131. selected_files = driver.find_element(By.ID, "selected_files")
  132. assert selected_files.text == "\n".join(exp_files)
  133. # do the upload
  134. upload_button.click()
  135. # look up the backend state and assert on uploaded contents
  136. backend_state = upload_file.app_instance.state_manager.states[token]
  137. time.sleep(0.5)
  138. for exp_name, exp_contents in exp_files.items():
  139. assert backend_state._file_data[exp_name] == exp_contents