test_background_task.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. """Test @rx.background task functionality."""
  2. from typing import Generator
  3. import pytest
  4. from selenium.webdriver.common.by import By
  5. from reflex.testing import DEFAULT_TIMEOUT, AppHarness, WebDriver
  6. def BackgroundTask():
  7. """Test that background tasks work as expected."""
  8. import asyncio
  9. import reflex as rx
  10. class State(rx.State):
  11. counter: int = 0
  12. _task_id: int = 0
  13. iterations: int = 10
  14. @rx.background
  15. async def handle_event(self):
  16. async with self:
  17. self._task_id += 1
  18. for _ix in range(int(self.iterations)):
  19. async with self:
  20. self.counter += 1
  21. await asyncio.sleep(0.005)
  22. @rx.background
  23. async def handle_event_yield_only(self):
  24. async with self:
  25. self._task_id += 1
  26. for ix in range(int(self.iterations)):
  27. if ix % 2 == 0:
  28. yield State.increment_arbitrary(1) # type: ignore
  29. else:
  30. yield State.increment() # type: ignore
  31. await asyncio.sleep(0.005)
  32. def increment(self):
  33. self.counter += 1
  34. @rx.background
  35. async def increment_arbitrary(self, amount: int):
  36. async with self:
  37. self.counter += int(amount)
  38. def reset_counter(self):
  39. self.counter = 0
  40. async def blocking_pause(self):
  41. await asyncio.sleep(0.02)
  42. @rx.background
  43. async def non_blocking_pause(self):
  44. await asyncio.sleep(0.02)
  45. def index() -> rx.Component:
  46. return rx.vstack(
  47. rx.input(
  48. id="token", value=State.router.session.client_token, is_read_only=True
  49. ),
  50. rx.heading(State.counter, id="counter"),
  51. rx.input(
  52. id="iterations",
  53. placeholder="Iterations",
  54. value=State.iterations.to_string(), # type: ignore
  55. on_change=State.set_iterations, # type: ignore
  56. ),
  57. rx.button(
  58. "Delayed Increment",
  59. on_click=State.handle_event,
  60. id="delayed-increment",
  61. ),
  62. rx.button(
  63. "Yield Increment",
  64. on_click=State.handle_event_yield_only,
  65. id="yield-increment",
  66. ),
  67. rx.button("Increment 1", on_click=State.increment, id="increment"),
  68. rx.button(
  69. "Blocking Pause",
  70. on_click=State.blocking_pause,
  71. id="blocking-pause",
  72. ),
  73. rx.button(
  74. "Non-Blocking Pause",
  75. on_click=State.non_blocking_pause,
  76. id="non-blocking-pause",
  77. ),
  78. rx.button("Reset", on_click=State.reset_counter, id="reset"),
  79. )
  80. app = rx.App(state=rx.State)
  81. app.add_page(index)
  82. app.compile()
  83. @pytest.fixture(scope="session")
  84. def background_task(
  85. tmp_path_factory,
  86. ) -> Generator[AppHarness, None, None]:
  87. """Start BackgroundTask app at tmp_path via AppHarness.
  88. Args:
  89. tmp_path_factory: pytest tmp_path_factory fixture
  90. Yields:
  91. running AppHarness instance
  92. """
  93. with AppHarness.create(
  94. root=tmp_path_factory.mktemp(f"background_task"),
  95. app_source=BackgroundTask, # type: ignore
  96. ) as harness:
  97. yield harness
  98. @pytest.fixture
  99. def driver(background_task: AppHarness) -> Generator[WebDriver, None, None]:
  100. """Get an instance of the browser open to the background_task app.
  101. Args:
  102. background_task: harness for BackgroundTask app
  103. Yields:
  104. WebDriver instance.
  105. """
  106. assert background_task.app_instance is not None, "app is not running"
  107. driver = background_task.frontend()
  108. try:
  109. yield driver
  110. finally:
  111. driver.quit()
  112. @pytest.fixture()
  113. def token(background_task: AppHarness, driver: WebDriver) -> str:
  114. """Get a function that returns the active token.
  115. Args:
  116. background_task: harness for BackgroundTask app.
  117. driver: WebDriver instance.
  118. Returns:
  119. The token for the connected client
  120. """
  121. assert background_task.app_instance is not None
  122. token_input = driver.find_element(By.ID, "token")
  123. assert token_input
  124. # wait for the backend connection to send the token
  125. token = background_task.poll_for_value(token_input, timeout=DEFAULT_TIMEOUT * 2)
  126. assert token is not None
  127. return token
  128. def test_background_task(
  129. background_task: AppHarness,
  130. driver: WebDriver,
  131. token: str,
  132. ):
  133. """Test that background tasks work as expected.
  134. Args:
  135. background_task: harness for BackgroundTask app.
  136. driver: WebDriver instance.
  137. token: The token for the connected client.
  138. """
  139. assert background_task.app_instance is not None
  140. # get a reference to all buttons
  141. delayed_increment_button = driver.find_element(By.ID, "delayed-increment")
  142. yield_increment_button = driver.find_element(By.ID, "yield-increment")
  143. increment_button = driver.find_element(By.ID, "increment")
  144. blocking_pause_button = driver.find_element(By.ID, "blocking-pause")
  145. non_blocking_pause_button = driver.find_element(By.ID, "non-blocking-pause")
  146. driver.find_element(By.ID, "reset")
  147. # get a reference to the counter
  148. counter = driver.find_element(By.ID, "counter")
  149. # get a reference to the iterations input
  150. iterations_input = driver.find_element(By.ID, "iterations")
  151. # kick off background tasks
  152. iterations_input.clear()
  153. iterations_input.send_keys("50")
  154. delayed_increment_button.click()
  155. blocking_pause_button.click()
  156. delayed_increment_button.click()
  157. for _ in range(10):
  158. increment_button.click()
  159. blocking_pause_button.click()
  160. delayed_increment_button.click()
  161. delayed_increment_button.click()
  162. yield_increment_button.click()
  163. non_blocking_pause_button.click()
  164. yield_increment_button.click()
  165. blocking_pause_button.click()
  166. yield_increment_button.click()
  167. for _ in range(10):
  168. increment_button.click()
  169. yield_increment_button.click()
  170. blocking_pause_button.click()
  171. assert background_task._poll_for(lambda: counter.text == "420", timeout=40)
  172. # all tasks should have exited and cleaned up
  173. assert background_task._poll_for(
  174. lambda: not background_task.app_instance.background_tasks # type: ignore
  175. )