test_background_task.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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 pytest
  10. import reflex_chakra as rc
  11. import reflex as rx
  12. from reflex.state import ImmutableStateError
  13. class State(rx.State):
  14. counter: int = 0
  15. _task_id: int = 0
  16. iterations: int = 10
  17. @rx.background
  18. async def handle_event(self):
  19. async with self:
  20. self._task_id += 1
  21. for _ix in range(int(self.iterations)):
  22. async with self:
  23. self.counter += 1
  24. await asyncio.sleep(0.005)
  25. @rx.background
  26. async def handle_event_yield_only(self):
  27. async with self:
  28. self._task_id += 1
  29. for ix in range(int(self.iterations)):
  30. if ix % 2 == 0:
  31. yield State.increment_arbitrary(1) # type: ignore
  32. else:
  33. yield State.increment() # type: ignore
  34. await asyncio.sleep(0.005)
  35. def increment(self):
  36. self.counter += 1
  37. @rx.background
  38. async def increment_arbitrary(self, amount: int):
  39. async with self:
  40. self.counter += int(amount)
  41. def reset_counter(self):
  42. self.counter = 0
  43. async def blocking_pause(self):
  44. await asyncio.sleep(0.02)
  45. @rx.background
  46. async def non_blocking_pause(self):
  47. await asyncio.sleep(0.02)
  48. async def racy_task(self):
  49. async with self:
  50. self._task_id += 1
  51. for _ix in range(int(self.iterations)):
  52. async with self:
  53. self.counter += 1
  54. await asyncio.sleep(0.005)
  55. @rx.background
  56. async def handle_racy_event(self):
  57. await asyncio.gather(
  58. self.racy_task(), self.racy_task(), self.racy_task(), self.racy_task()
  59. )
  60. @rx.background
  61. async def nested_async_with_self(self):
  62. async with self:
  63. self.counter += 1
  64. with pytest.raises(ImmutableStateError):
  65. async with self:
  66. self.counter += 1
  67. async def triple_count(self):
  68. third_state = await self.get_state(ThirdState)
  69. await third_state._triple_count()
  70. class OtherState(rx.State):
  71. @rx.background
  72. async def get_other_state(self):
  73. async with self:
  74. state = await self.get_state(State)
  75. state.counter += 1
  76. await state.triple_count()
  77. with pytest.raises(ImmutableStateError):
  78. await state.triple_count()
  79. with pytest.raises(ImmutableStateError):
  80. state.counter += 1
  81. async with state:
  82. state.counter += 1
  83. await state.triple_count()
  84. class ThirdState(rx.State):
  85. async def _triple_count(self):
  86. state = await self.get_state(State)
  87. state.counter *= 3
  88. def index() -> rx.Component:
  89. return rx.vstack(
  90. rc.input(
  91. id="token", value=State.router.session.client_token, is_read_only=True
  92. ),
  93. rx.heading(State.counter, id="counter"),
  94. rc.input(
  95. id="iterations",
  96. placeholder="Iterations",
  97. value=State.iterations.to_string(), # type: ignore
  98. on_change=State.set_iterations, # type: ignore
  99. ),
  100. rx.button(
  101. "Delayed Increment",
  102. on_click=State.handle_event,
  103. id="delayed-increment",
  104. ),
  105. rx.button(
  106. "Yield Increment",
  107. on_click=State.handle_event_yield_only,
  108. id="yield-increment",
  109. ),
  110. rx.button("Increment 1", on_click=State.increment, id="increment"),
  111. rx.button(
  112. "Blocking Pause",
  113. on_click=State.blocking_pause,
  114. id="blocking-pause",
  115. ),
  116. rx.button(
  117. "Non-Blocking Pause",
  118. on_click=State.non_blocking_pause,
  119. id="non-blocking-pause",
  120. ),
  121. rx.button(
  122. "Racy Increment (x4)",
  123. on_click=State.handle_racy_event,
  124. id="racy-increment",
  125. ),
  126. rx.button(
  127. "Nested Async with Self",
  128. on_click=State.nested_async_with_self,
  129. id="nested-async-with-self",
  130. ),
  131. rx.button(
  132. "Increment from OtherState",
  133. on_click=OtherState.get_other_state,
  134. id="increment-from-other-state",
  135. ),
  136. rx.button("Reset", on_click=State.reset_counter, id="reset"),
  137. )
  138. app = rx.App(state=rx.State)
  139. app.add_page(index)
  140. @pytest.fixture(scope="module")
  141. def background_task(
  142. tmp_path_factory,
  143. ) -> Generator[AppHarness, None, None]:
  144. """Start BackgroundTask app at tmp_path via AppHarness.
  145. Args:
  146. tmp_path_factory: pytest tmp_path_factory fixture
  147. Yields:
  148. running AppHarness instance
  149. """
  150. with AppHarness.create(
  151. root=tmp_path_factory.mktemp(f"background_task"),
  152. app_source=BackgroundTask, # type: ignore
  153. ) as harness:
  154. yield harness
  155. @pytest.fixture
  156. def driver(background_task: AppHarness) -> Generator[WebDriver, None, None]:
  157. """Get an instance of the browser open to the background_task app.
  158. Args:
  159. background_task: harness for BackgroundTask app
  160. Yields:
  161. WebDriver instance.
  162. """
  163. assert background_task.app_instance is not None, "app is not running"
  164. driver = background_task.frontend()
  165. try:
  166. yield driver
  167. finally:
  168. driver.quit()
  169. @pytest.fixture()
  170. def token(background_task: AppHarness, driver: WebDriver) -> str:
  171. """Get a function that returns the active token.
  172. Args:
  173. background_task: harness for BackgroundTask app.
  174. driver: WebDriver instance.
  175. Returns:
  176. The token for the connected client
  177. """
  178. assert background_task.app_instance is not None
  179. token_input = driver.find_element(By.ID, "token")
  180. assert token_input
  181. # wait for the backend connection to send the token
  182. token = background_task.poll_for_value(token_input, timeout=DEFAULT_TIMEOUT * 2)
  183. assert token is not None
  184. return token
  185. def test_background_task(
  186. background_task: AppHarness,
  187. driver: WebDriver,
  188. token: str,
  189. ):
  190. """Test that background tasks work as expected.
  191. Args:
  192. background_task: harness for BackgroundTask app.
  193. driver: WebDriver instance.
  194. token: The token for the connected client.
  195. """
  196. assert background_task.app_instance is not None
  197. # get a reference to all buttons
  198. delayed_increment_button = driver.find_element(By.ID, "delayed-increment")
  199. yield_increment_button = driver.find_element(By.ID, "yield-increment")
  200. increment_button = driver.find_element(By.ID, "increment")
  201. blocking_pause_button = driver.find_element(By.ID, "blocking-pause")
  202. non_blocking_pause_button = driver.find_element(By.ID, "non-blocking-pause")
  203. racy_increment_button = driver.find_element(By.ID, "racy-increment")
  204. driver.find_element(By.ID, "reset")
  205. # get a reference to the counter
  206. counter = driver.find_element(By.ID, "counter")
  207. # get a reference to the iterations input
  208. iterations_input = driver.find_element(By.ID, "iterations")
  209. # kick off background tasks
  210. iterations_input.clear()
  211. iterations_input.send_keys("50")
  212. delayed_increment_button.click()
  213. blocking_pause_button.click()
  214. delayed_increment_button.click()
  215. for _ in range(10):
  216. increment_button.click()
  217. blocking_pause_button.click()
  218. delayed_increment_button.click()
  219. delayed_increment_button.click()
  220. yield_increment_button.click()
  221. racy_increment_button.click()
  222. non_blocking_pause_button.click()
  223. yield_increment_button.click()
  224. blocking_pause_button.click()
  225. yield_increment_button.click()
  226. for _ in range(10):
  227. increment_button.click()
  228. yield_increment_button.click()
  229. blocking_pause_button.click()
  230. assert background_task._poll_for(lambda: counter.text == "620", timeout=40)
  231. # all tasks should have exited and cleaned up
  232. assert background_task._poll_for(
  233. lambda: not background_task.app_instance.background_tasks # type: ignore
  234. )
  235. def test_nested_async_with_self(
  236. background_task: AppHarness,
  237. driver: WebDriver,
  238. token: str,
  239. ):
  240. """Test that nested async with self in the same coroutine raises Exception.
  241. Args:
  242. background_task: harness for BackgroundTask app.
  243. driver: WebDriver instance.
  244. token: The token for the connected client.
  245. """
  246. assert background_task.app_instance is not None
  247. # get a reference to all buttons
  248. nested_async_with_self_button = driver.find_element(By.ID, "nested-async-with-self")
  249. increment_button = driver.find_element(By.ID, "increment")
  250. # get a reference to the counter
  251. counter = driver.find_element(By.ID, "counter")
  252. assert background_task._poll_for(lambda: counter.text == "0", timeout=5)
  253. nested_async_with_self_button.click()
  254. assert background_task._poll_for(lambda: counter.text == "1", timeout=5)
  255. increment_button.click()
  256. assert background_task._poll_for(lambda: counter.text == "2", timeout=5)
  257. def test_get_state(
  258. background_task: AppHarness,
  259. driver: WebDriver,
  260. token: str,
  261. ):
  262. """Test that get_state returns a state bound to the correct StateProxy.
  263. Args:
  264. background_task: harness for BackgroundTask app.
  265. driver: WebDriver instance.
  266. token: The token for the connected client.
  267. """
  268. assert background_task.app_instance is not None
  269. # get a reference to all buttons
  270. other_state_button = driver.find_element(By.ID, "increment-from-other-state")
  271. increment_button = driver.find_element(By.ID, "increment")
  272. # get a reference to the counter
  273. counter = driver.find_element(By.ID, "counter")
  274. assert background_task._poll_for(lambda: counter.text == "0", timeout=5)
  275. other_state_button.click()
  276. assert background_task._poll_for(lambda: counter.text == "12", timeout=5)
  277. increment_button.click()
  278. assert background_task._poll_for(lambda: counter.text == "13", timeout=5)