testing.py 34 KB

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