test_background_task.py 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  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.chakra.input(
  48. id="token", value=State.router.session.client_token, is_read_only=True
  49. ),
  50. rx.heading(State.counter, id="counter"),
  51. rx.chakra.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. @pytest.fixture(scope="module")
  83. def background_task(
  84. tmp_path_factory,
  85. ) -> Generator[AppHarness, None, None]:
  86. """Start BackgroundTask app at tmp_path via AppHarness.
  87. Args:
  88. tmp_path_factory: pytest tmp_path_factory fixture
  89. Yields:
  90. running AppHarness instance
  91. """
  92. with AppHarness.create(
  93. root=tmp_path_factory.mktemp(f"background_task"),
  94. app_source=BackgroundTask, # type: ignore
  95. ) as harness:
  96. yield harness
  97. @pytest.fixture
  98. def driver(background_task: AppHarness) -> Generator[WebDriver, None, None]:
  99. """Get an instance of the browser open to the background_task app.
  100. Args:
  101. background_task: harness for BackgroundTask app
  102. Yields:
  103. WebDriver instance.
  104. """
  105. assert background_task.app_instance is not None, "app is not running"
  106. driver = background_task.frontend()
  107. try:
  108. yield driver
  109. finally:
  110. driver.quit()
  111. @pytest.fixture()
  112. def token(background_task: AppHarness, driver: WebDriver) -> str:
  113. """Get a function that returns the active token.
  114. Args:
  115. background_task: harness for BackgroundTask app.
  116. driver: WebDriver instance.
  117. Returns:
  118. The token for the connected client
  119. """
  120. assert background_task.app_instance is not None
  121. token_input = driver.find_element(By.ID, "token")
  122. assert token_input
  123. # wait for the backend connection to send the token
  124. token = background_task.poll_for_value(token_input, timeout=DEFAULT_TIMEOUT * 2)
  125. assert token is not None
  126. return token
  127. def test_background_task(
  128. background_task: AppHarness,
  129. driver: WebDriver,
  130. token: str,
  131. ):
  132. """Test that background tasks work as expected.
  133. Args:
  134. background_task: harness for BackgroundTask app.
  135. driver: WebDriver instance.
  136. token: The token for the connected client.
  137. """
  138. assert background_task.app_instance is not None
  139. # get a reference to all buttons
  140. delayed_increment_button = driver.find_element(By.ID, "delayed-increment")
  141. yield_increment_button = driver.find_element(By.ID, "yield-increment")
  142. increment_button = driver.find_element(By.ID, "increment")
  143. blocking_pause_button = driver.find_element(By.ID, "blocking-pause")
  144. non_blocking_pause_button = driver.find_element(By.ID, "non-blocking-pause")
  145. driver.find_element(By.ID, "reset")
  146. # get a reference to the counter
  147. counter = driver.find_element(By.ID, "counter")
  148. # get a reference to the iterations input
  149. iterations_input = driver.find_element(By.ID, "iterations")
  150. # kick off background tasks
  151. iterations_input.clear()
  152. iterations_input.send_keys("50")
  153. delayed_increment_button.click()
  154. blocking_pause_button.click()
  155. delayed_increment_button.click()
  156. for _ in range(10):
  157. increment_button.click()
  158. blocking_pause_button.click()
  159. delayed_increment_button.click()
  160. delayed_increment_button.click()
  161. yield_increment_button.click()
  162. non_blocking_pause_button.click()
  163. yield_increment_button.click()
  164. blocking_pause_button.click()
  165. yield_increment_button.click()
  166. for _ in range(10):
  167. increment_button.click()
  168. yield_increment_button.click()
  169. blocking_pause_button.click()
  170. assert background_task._poll_for(lambda: counter.text == "420", timeout=40)
  171. # all tasks should have exited and cleaned up
  172. assert background_task._poll_for(
  173. lambda: not background_task.app_instance.background_tasks # type: ignore
  174. )