testing.py 34 KB

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