testing.py 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. """reflex.testing - tools for testing reflex apps."""
  2. from __future__ import annotations
  3. import asyncio
  4. import contextlib
  5. import dataclasses
  6. import functools
  7. import inspect
  8. import os
  9. import pathlib
  10. import platform
  11. import re
  12. import signal
  13. import socket
  14. import socketserver
  15. import subprocess
  16. import textwrap
  17. import threading
  18. import time
  19. import types
  20. from http.server import SimpleHTTPRequestHandler
  21. from typing import (
  22. TYPE_CHECKING,
  23. Any,
  24. AsyncIterator,
  25. Callable,
  26. Coroutine,
  27. List,
  28. Optional,
  29. Type,
  30. TypeVar,
  31. Union,
  32. )
  33. import psutil
  34. import uvicorn
  35. import reflex
  36. import reflex.reflex
  37. import reflex.utils.build
  38. import reflex.utils.exec
  39. import reflex.utils.prerequisites
  40. import reflex.utils.processes
  41. from reflex.state import (
  42. BaseState,
  43. StateManagerMemory,
  44. StateManagerRedis,
  45. reload_state_module,
  46. )
  47. try:
  48. from selenium import webdriver # pyright: ignore [reportMissingImports]
  49. from selenium.webdriver.remote.webdriver import ( # pyright: ignore [reportMissingImports]
  50. WebDriver,
  51. )
  52. if TYPE_CHECKING:
  53. from selenium.webdriver.common.options import (
  54. ArgOptions, # pyright: ignore [reportMissingImports]
  55. )
  56. from selenium.webdriver.remote.webelement import ( # pyright: ignore [reportMissingImports]
  57. WebElement,
  58. )
  59. has_selenium = True
  60. except ImportError:
  61. has_selenium = False
  62. # The timeout (minutes) to check for the port.
  63. DEFAULT_TIMEOUT = 15
  64. POLL_INTERVAL = 0.25
  65. FRONTEND_POPEN_ARGS = {}
  66. T = TypeVar("T")
  67. TimeoutType = Optional[Union[int, float]]
  68. if platform.system() == "Windows":
  69. FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # type: ignore
  70. FRONTEND_POPEN_ARGS["shell"] = True
  71. else:
  72. FRONTEND_POPEN_ARGS["start_new_session"] = True
  73. # borrowed from py3.11
  74. class chdir(contextlib.AbstractContextManager):
  75. """Non thread-safe context manager to change the current working directory."""
  76. def __init__(self, path):
  77. """Prepare contextmanager.
  78. Args:
  79. path: the path to change to
  80. """
  81. self.path = path
  82. self._old_cwd = []
  83. def __enter__(self):
  84. """Save current directory and perform chdir."""
  85. self._old_cwd.append(os.getcwd())
  86. os.chdir(self.path)
  87. def __exit__(self, *excinfo):
  88. """Change back to previous directory on stack.
  89. Args:
  90. excinfo: sys.exc_info captured in the context block
  91. """
  92. os.chdir(self._old_cwd.pop())
  93. @dataclasses.dataclass
  94. class AppHarness:
  95. """AppHarness executes a reflex app in-process for testing."""
  96. app_name: str
  97. app_source: Optional[
  98. types.FunctionType | types.ModuleType | str | functools.partial
  99. ]
  100. app_path: pathlib.Path
  101. app_module_path: pathlib.Path
  102. app_module: Optional[types.ModuleType] = None
  103. app_instance: Optional[reflex.App] = None
  104. frontend_process: Optional[subprocess.Popen] = None
  105. frontend_url: Optional[str] = None
  106. frontend_output_thread: Optional[threading.Thread] = None
  107. backend_thread: Optional[threading.Thread] = None
  108. backend: Optional[uvicorn.Server] = None
  109. state_manager: Optional[StateManagerMemory | StateManagerRedis] = None
  110. _frontends: list["WebDriver"] = dataclasses.field(default_factory=list)
  111. _decorated_pages: list = dataclasses.field(default_factory=list)
  112. @classmethod
  113. def create(
  114. cls,
  115. root: pathlib.Path,
  116. app_source: Optional[types.FunctionType | types.ModuleType | str] = None,
  117. app_name: Optional[str] = None,
  118. ) -> "AppHarness":
  119. """Create an AppHarness instance at root.
  120. Args:
  121. root: the directory that will contain the app under test.
  122. app_source: if specified, the source code from this function or module is used
  123. as the main module for the app. It may also be the raw source code text, as a str.
  124. If unspecified, then root must already contain a working reflex app and will be used directly.
  125. app_name: provide the name of the app, otherwise will be derived from app_source or root.
  126. Raises:
  127. ValueError: when app_source is a string and app_name is not provided.
  128. Returns:
  129. AppHarness instance
  130. """
  131. if app_name is None:
  132. if app_source is None:
  133. app_name = root.name
  134. elif isinstance(app_source, functools.partial):
  135. keywords = app_source.keywords
  136. slug_suffix = "_".join([str(v) for v in keywords.values()])
  137. func_name = app_source.func.__name__
  138. app_name = f"{func_name}_{slug_suffix}"
  139. app_name = re.sub(r"[^a-zA-Z0-9_]", "_", app_name)
  140. elif isinstance(app_source, str):
  141. raise ValueError(
  142. "app_name must be provided when app_source is a string."
  143. )
  144. else:
  145. app_name = app_source.__name__
  146. app_name = app_name.lower()
  147. while "__" in app_name:
  148. app_name = app_name.replace("__", "_")
  149. return cls(
  150. app_name=app_name,
  151. app_source=app_source,
  152. app_path=root,
  153. app_module_path=root / app_name / f"{app_name}.py",
  154. )
  155. def _get_globals_from_signature(self, func: Any) -> dict[str, Any]:
  156. """Get the globals from a function or module object.
  157. Args:
  158. func: function or module object
  159. Returns:
  160. dict of globals
  161. """
  162. overrides = {}
  163. glbs = {}
  164. if not callable(func):
  165. return glbs
  166. if isinstance(func, functools.partial):
  167. overrides = func.keywords
  168. func = func.func
  169. for param in inspect.signature(func).parameters.values():
  170. if param.default is not inspect.Parameter.empty:
  171. glbs[param.name] = param.default
  172. glbs.update(overrides)
  173. return glbs
  174. def _get_source_from_app_source(self, app_source: Any) -> str:
  175. """Get the source from app_source.
  176. Args:
  177. app_source: function or module or str
  178. Returns:
  179. source code
  180. """
  181. if isinstance(app_source, str):
  182. return app_source
  183. source = inspect.getsource(app_source)
  184. source = re.sub(
  185. r"^\s*def\s+\w+\s*\(.*?\)(\s+->\s+\w+)?:", "", source, flags=re.DOTALL
  186. )
  187. return textwrap.dedent(source)
  188. def _initialize_app(self):
  189. os.environ["TELEMETRY_ENABLED"] = "" # disable telemetry reporting for tests
  190. self.app_path.mkdir(parents=True, exist_ok=True)
  191. if self.app_source is not None:
  192. app_globals = self._get_globals_from_signature(self.app_source)
  193. if isinstance(self.app_source, functools.partial):
  194. self.app_source = self.app_source.func # type: ignore
  195. # get the source from a function or module object
  196. source_code = "\n".join(
  197. [
  198. "\n".join(
  199. self.get_app_global_source(k, v) for k, v in app_globals.items()
  200. ),
  201. self._get_source_from_app_source(self.app_source),
  202. ]
  203. )
  204. with chdir(self.app_path):
  205. reflex.reflex._init(
  206. name=self.app_name,
  207. template=reflex.constants.Templates.DEFAULT,
  208. loglevel=reflex.constants.LogLevel.INFO,
  209. )
  210. self.app_module_path.write_text(source_code)
  211. with chdir(self.app_path):
  212. # ensure config and app are reloaded when testing different app
  213. reflex.config.get_config(reload=True)
  214. # Save decorated pages before importing the test app module
  215. before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
  216. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  217. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  218. self.app_module = reflex.utils.prerequisites.get_compiled_app(reload=True)
  219. # Save the pages that were added during testing
  220. self._decorated_pages = [
  221. p
  222. for p in reflex.app.DECORATED_PAGES[self.app_name]
  223. if p not in before_decorated_pages
  224. ]
  225. self.app_instance = self.app_module.app
  226. if isinstance(self.app_instance._state_manager, StateManagerRedis):
  227. # Create our own redis connection for testing.
  228. self.state_manager = StateManagerRedis.create(self.app_instance.state)
  229. else:
  230. self.state_manager = self.app_instance._state_manager
  231. def _reload_state_module(self):
  232. """Reload the rx.State module to avoid conflict when reloading."""
  233. reload_state_module(module=f"{self.app_name}.{self.app_name}")
  234. def _get_backend_shutdown_handler(self):
  235. if self.backend is None:
  236. raise RuntimeError("Backend was not initialized.")
  237. original_shutdown = self.backend.shutdown
  238. async def _shutdown_redis(*args, **kwargs) -> None:
  239. # ensure redis is closed before event loop
  240. try:
  241. if self.app_instance is not None and isinstance(
  242. self.app_instance.state_manager, StateManagerRedis
  243. ):
  244. await self.app_instance.state_manager.close()
  245. except ValueError:
  246. pass
  247. await original_shutdown(*args, **kwargs)
  248. return _shutdown_redis
  249. def _start_backend(self, port=0):
  250. if self.app_instance is None:
  251. raise RuntimeError("App was not initialized.")
  252. self.backend = uvicorn.Server(
  253. uvicorn.Config(
  254. app=self.app_instance.api,
  255. host="127.0.0.1",
  256. port=port,
  257. )
  258. )
  259. self.backend.shutdown = self._get_backend_shutdown_handler()
  260. self.backend_thread = threading.Thread(target=self.backend.run)
  261. self.backend_thread.start()
  262. async def _reset_backend_state_manager(self):
  263. """Reset the StateManagerRedis event loop affinity.
  264. This is necessary when the backend is restarted and the state manager is a
  265. StateManagerRedis instance.
  266. """
  267. if (
  268. self.app_instance is not None
  269. and isinstance(
  270. self.app_instance.state_manager,
  271. StateManagerRedis,
  272. )
  273. and self.app_instance.state is not None
  274. ):
  275. with contextlib.suppress(RuntimeError):
  276. await self.app_instance.state_manager.close()
  277. self.app_instance._state_manager = StateManagerRedis.create(
  278. state=self.app_instance.state,
  279. )
  280. assert isinstance(self.app_instance.state_manager, StateManagerRedis)
  281. def _start_frontend(self):
  282. # Set up the frontend.
  283. with chdir(self.app_path):
  284. config = reflex.config.get_config()
  285. config.api_url = "http://{0}:{1}".format(
  286. *self._poll_for_servers().getsockname(),
  287. )
  288. reflex.utils.build.setup_frontend(self.app_path)
  289. # Start the frontend.
  290. self.frontend_process = reflex.utils.processes.new_process(
  291. [reflex.utils.prerequisites.get_package_manager(), "run", "dev"],
  292. cwd=self.app_path / reflex.constants.Dirs.WEB,
  293. env={"PORT": "0"},
  294. **FRONTEND_POPEN_ARGS,
  295. )
  296. def _wait_frontend(self):
  297. while self.frontend_url is None:
  298. line = (
  299. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  300. )
  301. if not line:
  302. break
  303. print(line) # for pytest diagnosis
  304. m = re.search(reflex.constants.Next.FRONTEND_LISTENING_REGEX, line)
  305. if m is not None:
  306. self.frontend_url = m.group(1)
  307. config = reflex.config.get_config()
  308. config.deploy_url = self.frontend_url
  309. break
  310. if self.frontend_url is None:
  311. raise RuntimeError("Frontend did not start")
  312. def consume_frontend_output():
  313. while True:
  314. line = (
  315. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  316. )
  317. if not line:
  318. break
  319. print(line)
  320. self.frontend_output_thread = threading.Thread(target=consume_frontend_output)
  321. self.frontend_output_thread.start()
  322. def start(self) -> "AppHarness":
  323. """Start the backend in a new thread and dev frontend as a separate process.
  324. Returns:
  325. self
  326. """
  327. self._initialize_app()
  328. self._start_backend()
  329. self._start_frontend()
  330. self._wait_frontend()
  331. return self
  332. @staticmethod
  333. def get_app_global_source(key, value):
  334. """Get the source code of a global object.
  335. If value is a function or class we render the actual
  336. source of value otherwise we assign value to key.
  337. Args:
  338. key: variable name to assign value to.
  339. value: value of the global variable.
  340. Returns:
  341. The rendered app global code.
  342. """
  343. if not inspect.isclass(value) and not inspect.isfunction(value):
  344. return f"{key} = {value!r}"
  345. return inspect.getsource(value)
  346. def __enter__(self) -> "AppHarness":
  347. """Contextmanager protocol for `start()`.
  348. Returns:
  349. Instance of AppHarness after calling start()
  350. """
  351. return self.start()
  352. def stop(self) -> None:
  353. """Stop the frontend and backend servers."""
  354. self._reload_state_module()
  355. if self.backend is not None:
  356. self.backend.should_exit = True
  357. if self.frontend_process is not None:
  358. # https://stackoverflow.com/a/70565806
  359. frontend_children = psutil.Process(self.frontend_process.pid).children(
  360. recursive=True,
  361. )
  362. if platform.system() == "Windows":
  363. self.frontend_process.terminate()
  364. else:
  365. pgrp = os.getpgid(self.frontend_process.pid)
  366. os.killpg(pgrp, signal.SIGTERM)
  367. # kill any remaining child processes
  368. for child in frontend_children:
  369. # It's okay if the process is already gone.
  370. with contextlib.suppress(psutil.NoSuchProcess):
  371. child.terminate()
  372. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  373. for child in still_alive:
  374. # It's okay if the process is already gone.
  375. with contextlib.suppress(psutil.NoSuchProcess):
  376. child.kill()
  377. # wait for main process to exit
  378. self.frontend_process.communicate()
  379. if self.backend_thread is not None:
  380. self.backend_thread.join()
  381. if self.frontend_output_thread is not None:
  382. self.frontend_output_thread.join()
  383. for driver in self._frontends:
  384. driver.quit()
  385. # Cleanup decorated pages added during testing
  386. for page in self._decorated_pages:
  387. reflex.app.DECORATED_PAGES[self.app_name].remove(page)
  388. def __exit__(self, *excinfo) -> None:
  389. """Contextmanager protocol for `stop()`.
  390. Args:
  391. excinfo: sys.exc_info captured in the context block
  392. """
  393. self.stop()
  394. @staticmethod
  395. def _poll_for(
  396. target: Callable[[], T],
  397. timeout: TimeoutType = None,
  398. step: TimeoutType = None,
  399. ) -> T | bool:
  400. """Generic polling logic.
  401. Args:
  402. target: callable that returns truthy if polling condition is met.
  403. timeout: max polling time
  404. step: interval between checking target()
  405. Returns:
  406. return value of target() if truthy within timeout
  407. False if timeout elapses
  408. """
  409. if timeout is None:
  410. timeout = DEFAULT_TIMEOUT
  411. if step is None:
  412. step = POLL_INTERVAL
  413. deadline = time.time() + timeout
  414. while time.time() < deadline:
  415. success = target()
  416. if success:
  417. return success
  418. time.sleep(step)
  419. return False
  420. @staticmethod
  421. async def _poll_for_async(
  422. target: Callable[[], Coroutine[None, None, T]],
  423. timeout: TimeoutType = None,
  424. step: TimeoutType = None,
  425. ) -> T | bool:
  426. """Generic polling logic for async functions.
  427. Args:
  428. target: callable that returns truthy if polling condition is met.
  429. timeout: max polling time
  430. step: interval between checking target()
  431. Returns:
  432. return value of target() if truthy within timeout
  433. False if timeout elapses
  434. """
  435. if timeout is None:
  436. timeout = DEFAULT_TIMEOUT
  437. if step is None:
  438. step = POLL_INTERVAL
  439. deadline = time.time() + timeout
  440. while time.time() < deadline:
  441. success = await target()
  442. if success:
  443. return success
  444. await asyncio.sleep(step)
  445. return False
  446. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  447. """Poll backend server for listening sockets.
  448. Args:
  449. timeout: how long to wait for listening socket.
  450. Returns:
  451. first active listening socket on the backend
  452. Raises:
  453. RuntimeError: when the backend hasn't started running
  454. TimeoutError: when server or sockets are not ready
  455. """
  456. if self.backend is None:
  457. raise RuntimeError("Backend is not running.")
  458. backend = self.backend
  459. # check for servers to be initialized
  460. if not self._poll_for(
  461. target=lambda: getattr(backend, "servers", False),
  462. timeout=timeout,
  463. ):
  464. raise TimeoutError("Backend servers are not initialized.")
  465. # check for sockets to be listening
  466. if not self._poll_for(
  467. target=lambda: getattr(backend.servers[0], "sockets", False),
  468. timeout=timeout,
  469. ):
  470. raise TimeoutError("Backend is not listening.")
  471. return backend.servers[0].sockets[0]
  472. def frontend(
  473. self,
  474. driver_clz: Optional[Type["WebDriver"]] = None,
  475. driver_kwargs: dict[str, Any] | None = None,
  476. driver_options: ArgOptions | None = None,
  477. driver_option_args: List[str] | None = None,
  478. driver_option_capabilities: dict[str, Any] | None = None,
  479. ) -> "WebDriver":
  480. """Get a selenium webdriver instance pointed at the app.
  481. Args:
  482. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  483. webdriver.Edge, etc
  484. driver_kwargs: additional keyword arguments to pass to the webdriver constructor
  485. driver_options: selenium ArgOptions instance to pass to the webdriver constructor
  486. driver_option_args: additional arguments for the webdriver options
  487. driver_option_capabilities: additional capabilities for the webdriver options
  488. Returns:
  489. Instance of the given webdriver navigated to the frontend url of the app.
  490. Raises:
  491. RuntimeError: when selenium is not importable or frontend is not running
  492. """
  493. if not has_selenium:
  494. raise RuntimeError(
  495. "Frontend functionality requires `selenium` to be installed, "
  496. "and it could not be imported."
  497. )
  498. if self.frontend_url is None:
  499. raise RuntimeError("Frontend is not running.")
  500. want_headless = False
  501. if os.environ.get("APP_HARNESS_HEADLESS"):
  502. want_headless = True
  503. if driver_clz is None:
  504. requested_driver = os.environ.get("APP_HARNESS_DRIVER", "Chrome")
  505. driver_clz = getattr(webdriver, requested_driver)
  506. if driver_options is None:
  507. driver_options = getattr(webdriver, f"{requested_driver}Options")()
  508. if driver_clz is webdriver.Chrome:
  509. if driver_options is None:
  510. driver_options = webdriver.ChromeOptions()
  511. driver_options.add_argument("--class=AppHarness")
  512. if want_headless:
  513. driver_options.add_argument("--headless=new")
  514. elif driver_clz is webdriver.Firefox:
  515. if driver_options is None:
  516. driver_options = webdriver.FirefoxOptions()
  517. if want_headless:
  518. driver_options.add_argument("-headless")
  519. elif driver_clz is webdriver.Edge:
  520. if driver_options is None:
  521. driver_options = webdriver.EdgeOptions()
  522. if want_headless:
  523. driver_options.add_argument("headless")
  524. if driver_options is None:
  525. raise RuntimeError(f"Could not determine options for {driver_clz}")
  526. if args := os.environ.get("APP_HARNESS_DRIVER_ARGS"):
  527. for arg in args.split(","):
  528. driver_options.add_argument(arg)
  529. if driver_option_args is not None:
  530. for arg in driver_option_args:
  531. driver_options.add_argument(arg)
  532. if driver_option_capabilities is not None:
  533. for key, value in driver_option_capabilities.items():
  534. driver_options.set_capability(key, value)
  535. if driver_kwargs is None:
  536. driver_kwargs = {}
  537. driver = driver_clz(options=driver_options, **driver_kwargs) # type: ignore
  538. driver.get(self.frontend_url)
  539. self._frontends.append(driver)
  540. return driver
  541. async def get_state(self, token: str) -> BaseState:
  542. """Get the state associated with the given token.
  543. Args:
  544. token: The state token to look up.
  545. Returns:
  546. The state instance associated with the given token
  547. Raises:
  548. RuntimeError: when the app hasn't started running
  549. """
  550. if self.state_manager is None:
  551. raise RuntimeError("state_manager is not set.")
  552. try:
  553. return await self.state_manager.get_state(token)
  554. finally:
  555. if isinstance(self.state_manager, StateManagerRedis):
  556. await self.state_manager.close()
  557. async def set_state(self, token: str, **kwargs) -> None:
  558. """Set the state associated with the given token.
  559. Args:
  560. token: The state token to set.
  561. kwargs: Attributes to set on the state.
  562. Raises:
  563. RuntimeError: when the app hasn't started running
  564. """
  565. if self.state_manager is None:
  566. raise RuntimeError("state_manager is not set.")
  567. state = await self.get_state(token)
  568. for key, value in kwargs.items():
  569. setattr(state, key, value)
  570. try:
  571. await self.state_manager.set_state(token, state)
  572. finally:
  573. if isinstance(self.state_manager, StateManagerRedis):
  574. await self.state_manager.close()
  575. @contextlib.asynccontextmanager
  576. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  577. """Modify the state associated with the given token and send update to frontend.
  578. Args:
  579. token: The state token to modify
  580. Yields:
  581. The state instance associated with the given token
  582. Raises:
  583. RuntimeError: when the app hasn't started running
  584. """
  585. if self.state_manager is None:
  586. raise RuntimeError("state_manager is not set.")
  587. if self.app_instance is None:
  588. raise RuntimeError("App is not running.")
  589. app_state_manager = self.app_instance.state_manager
  590. if isinstance(self.state_manager, StateManagerRedis):
  591. # Temporarily replace the app's state manager with our own, since
  592. # the redis connection is on the backend_thread event loop
  593. self.app_instance._state_manager = self.state_manager
  594. try:
  595. async with self.app_instance.modify_state(token) as state:
  596. yield state
  597. finally:
  598. if isinstance(self.state_manager, StateManagerRedis):
  599. self.app_instance._state_manager = app_state_manager
  600. await self.state_manager.close()
  601. def poll_for_content(
  602. self,
  603. element: "WebElement",
  604. timeout: TimeoutType = None,
  605. exp_not_equal: str = "",
  606. ) -> str:
  607. """Poll element.text for change.
  608. Args:
  609. element: selenium webdriver element to check
  610. timeout: how long to poll element.text
  611. exp_not_equal: exit the polling loop when the element text does not match
  612. Returns:
  613. The element text when the polling loop exited
  614. Raises:
  615. TimeoutError: when the timeout expires before text changes
  616. """
  617. if not self._poll_for(
  618. target=lambda: element.text != exp_not_equal,
  619. timeout=timeout,
  620. ):
  621. raise TimeoutError(
  622. f"{element} content remains {exp_not_equal!r} while polling.",
  623. )
  624. return element.text
  625. def poll_for_value(
  626. self,
  627. element: "WebElement",
  628. timeout: TimeoutType = None,
  629. exp_not_equal: str = "",
  630. ) -> Optional[str]:
  631. """Poll element.get_attribute("value") for change.
  632. Args:
  633. element: selenium webdriver element to check
  634. timeout: how long to poll element value attribute
  635. exp_not_equal: exit the polling loop when the value does not match
  636. Returns:
  637. The element value when the polling loop exited
  638. Raises:
  639. TimeoutError: when the timeout expires before value changes
  640. """
  641. if not self._poll_for(
  642. target=lambda: element.get_attribute("value") != exp_not_equal,
  643. timeout=timeout,
  644. ):
  645. raise TimeoutError(
  646. f"{element} content remains {exp_not_equal!r} while polling.",
  647. )
  648. return element.get_attribute("value")
  649. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
  650. """Poll app state_manager for any connected clients.
  651. Args:
  652. timeout: how long to wait for client states
  653. Returns:
  654. active state instances when the polling loop exited
  655. Raises:
  656. RuntimeError: when the app hasn't started running
  657. TimeoutError: when the timeout expires before any states are seen
  658. """
  659. if self.app_instance is None:
  660. raise RuntimeError("App is not running.")
  661. state_manager = self.app_instance.state_manager
  662. assert isinstance(
  663. state_manager, StateManagerMemory
  664. ), "Only works with memory state manager"
  665. if not self._poll_for(
  666. target=lambda: state_manager.states,
  667. timeout=timeout,
  668. ):
  669. raise TimeoutError("No states were observed while polling.")
  670. return state_manager.states
  671. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  672. """SimpleHTTPRequestHandler with custom error page handling."""
  673. def __init__(self, *args, error_page_map: dict[int, pathlib.Path], **kwargs):
  674. """Initialize the handler.
  675. Args:
  676. error_page_map: map of error code to error page path
  677. *args: passed through to superclass
  678. **kwargs: passed through to superclass
  679. """
  680. self.error_page_map = error_page_map
  681. super().__init__(*args, **kwargs)
  682. def send_error(
  683. self, code: int, message: str | None = None, explain: str | None = None
  684. ) -> None:
  685. """Send the error page for the given error code.
  686. If the code matches a custom error page, then message and explain are
  687. ignored.
  688. Args:
  689. code: the error code
  690. message: the error message
  691. explain: the error explanation
  692. """
  693. error_page = self.error_page_map.get(code)
  694. if error_page:
  695. self.send_response(code, message)
  696. self.send_header("Connection", "close")
  697. body = error_page.read_bytes()
  698. self.send_header("Content-Type", self.error_content_type)
  699. self.send_header("Content-Length", str(len(body)))
  700. self.end_headers()
  701. self.wfile.write(body)
  702. else:
  703. super().send_error(code, message, explain)
  704. class Subdir404TCPServer(socketserver.TCPServer):
  705. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  706. def __init__(
  707. self,
  708. *args,
  709. root: pathlib.Path,
  710. error_page_map: dict[int, pathlib.Path] | None,
  711. **kwargs,
  712. ):
  713. """Initialize the server.
  714. Args:
  715. root: the root directory to serve from
  716. error_page_map: map of error code to error page path
  717. *args: passed through to superclass
  718. **kwargs: passed through to superclass
  719. """
  720. self.root = root
  721. self.error_page_map = error_page_map or {}
  722. super().__init__(*args, **kwargs)
  723. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  724. """Finish one request by instantiating RequestHandlerClass.
  725. Args:
  726. request: the requesting socket
  727. client_address: (host, port) referring to the client’s address.
  728. """
  729. self.RequestHandlerClass(
  730. request,
  731. client_address,
  732. self,
  733. directory=str(self.root), # type: ignore
  734. error_page_map=self.error_page_map, # type: ignore
  735. )
  736. class AppHarnessProd(AppHarness):
  737. """AppHarnessProd executes a reflex app in-process for testing.
  738. In prod mode, instead of running `next dev` the app is exported as static
  739. files and served via the builtin python http.server with custom 404 redirect
  740. handling. Additionally, the backend runs in multi-worker mode.
  741. """
  742. frontend_thread: Optional[threading.Thread] = None
  743. frontend_server: Optional[Subdir404TCPServer] = None
  744. def _run_frontend(self):
  745. web_root = self.app_path / reflex.constants.Dirs.WEB_STATIC
  746. error_page_map = {
  747. 404: web_root / "404.html",
  748. }
  749. with Subdir404TCPServer(
  750. ("", 0),
  751. SimpleHTTPRequestHandlerCustomErrors,
  752. root=web_root,
  753. error_page_map=error_page_map,
  754. ) as self.frontend_server:
  755. self.frontend_url = "http://localhost:{1}".format(
  756. *self.frontend_server.socket.getsockname()
  757. )
  758. self.frontend_server.serve_forever()
  759. def _start_frontend(self):
  760. # Set up the frontend.
  761. with chdir(self.app_path):
  762. config = reflex.config.get_config()
  763. config.api_url = "http://{0}:{1}".format(
  764. *self._poll_for_servers().getsockname(),
  765. )
  766. reflex.reflex.export(
  767. zipping=False,
  768. frontend=True,
  769. backend=False,
  770. loglevel=reflex.constants.LogLevel.INFO,
  771. )
  772. self.frontend_thread = threading.Thread(target=self._run_frontend)
  773. self.frontend_thread.start()
  774. def _wait_frontend(self):
  775. self._poll_for(lambda: self.frontend_server is not None)
  776. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  777. raise RuntimeError("Frontend did not start")
  778. def _start_backend(self):
  779. if self.app_instance is None:
  780. raise RuntimeError("App was not initialized.")
  781. os.environ[reflex.constants.SKIP_COMPILE_ENV_VAR] = "yes"
  782. self.backend = uvicorn.Server(
  783. uvicorn.Config(
  784. app=self.app_instance,
  785. host="127.0.0.1",
  786. port=0,
  787. workers=reflex.utils.processes.get_num_workers(),
  788. ),
  789. )
  790. self.backend.shutdown = self._get_backend_shutdown_handler()
  791. self.backend_thread = threading.Thread(target=self.backend.run)
  792. self.backend_thread.start()
  793. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  794. try:
  795. return super()._poll_for_servers(timeout)
  796. finally:
  797. os.environ.pop(reflex.constants.SKIP_COMPILE_ENV_VAR, None)
  798. def stop(self):
  799. """Stop the frontend python webserver."""
  800. super().stop()
  801. if self.frontend_server is not None:
  802. self.frontend_server.shutdown()
  803. if self.frontend_thread is not None:
  804. self.frontend_thread.join()