testing.py 35 KB

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