testing.py 35 KB

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