testing.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981
  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. _decorated_pages: list = dataclasses.field(default_factory=list)
  102. @classmethod
  103. def create(
  104. cls,
  105. root: Path,
  106. app_source: (
  107. Callable[[], None] | types.ModuleType | str | functools.partial[Any] | None
  108. ) = None,
  109. app_name: str | None = None,
  110. ) -> AppHarness:
  111. """Create an AppHarness instance at root.
  112. Args:
  113. root: the directory that will contain the app under test.
  114. app_source: if specified, the source code from this function or module is used
  115. as the main module for the app. It may also be the raw source code text, as a str.
  116. If unspecified, then root must already contain a working reflex app and will be used directly.
  117. app_name: provide the name of the app, otherwise will be derived from app_source or root.
  118. Raises:
  119. ValueError: when app_source is a string and app_name is not provided.
  120. Returns:
  121. AppHarness instance
  122. """
  123. if app_name is None:
  124. if app_source is None:
  125. app_name = root.name
  126. elif isinstance(app_source, functools.partial):
  127. keywords = app_source.keywords
  128. slug_suffix = "_".join([str(v) for v in keywords.values()])
  129. func_name = app_source.func.__name__
  130. app_name = f"{func_name}_{slug_suffix}"
  131. app_name = re.sub(r"[^a-zA-Z0-9_]", "_", app_name)
  132. elif isinstance(app_source, str):
  133. raise ValueError(
  134. "app_name must be provided when app_source is a string."
  135. )
  136. else:
  137. app_name = app_source.__name__
  138. app_name = app_name.lower()
  139. while "__" in app_name:
  140. app_name = app_name.replace("__", "_")
  141. return cls(
  142. app_name=app_name,
  143. app_source=app_source,
  144. app_path=root,
  145. app_module_path=root / app_name / f"{app_name}.py",
  146. )
  147. def get_state_name(self, state_cls_name: str) -> str:
  148. """Get the state name for the given state class name.
  149. Args:
  150. state_cls_name: The state class name
  151. Returns:
  152. The state name
  153. """
  154. return reflex.utils.format.to_snake_case(
  155. f"{self.app_name}___{self.app_name}___" + state_cls_name
  156. )
  157. def get_full_state_name(self, path: list[str]) -> str:
  158. """Get the full state name for the given state class name.
  159. Args:
  160. path: A list of state class names
  161. Returns:
  162. The full state name
  163. """
  164. # NOTE: using State.get_name() somehow causes trouble here
  165. # path = [State.get_name()] + [self.get_state_name(p) for p in path] # noqa: ERA001
  166. path = ["reflex___state____state"] + [self.get_state_name(p) for p in path]
  167. return ".".join(path)
  168. def _get_globals_from_signature(self, func: Any) -> dict[str, Any]:
  169. """Get the globals from a function or module object.
  170. Args:
  171. func: function or module object
  172. Returns:
  173. dict of globals
  174. """
  175. overrides = {}
  176. glbs = {}
  177. if not callable(func):
  178. return glbs
  179. if isinstance(func, functools.partial):
  180. overrides = func.keywords
  181. func = func.func
  182. for param in inspect.signature(func).parameters.values():
  183. if param.default is not inspect.Parameter.empty:
  184. glbs[param.name] = param.default
  185. glbs.update(overrides)
  186. return glbs
  187. def _get_source_from_app_source(self, app_source: Any) -> str:
  188. """Get the source from app_source.
  189. Args:
  190. app_source: function or module or str
  191. Returns:
  192. source code
  193. """
  194. if isinstance(app_source, str):
  195. return app_source
  196. source = inspect.getsource(app_source)
  197. source = re.sub(
  198. r"^\s*def\s+\w+\s*\(.*?\)(\s+->\s+\w+)?:", "", source, flags=re.DOTALL
  199. )
  200. return textwrap.dedent(source)
  201. def _initialize_app(self):
  202. # disable telemetry reporting for tests
  203. os.environ["TELEMETRY_ENABLED"] = "false"
  204. CustomComponent.create().get_component.cache_clear()
  205. self.app_path.mkdir(parents=True, exist_ok=True)
  206. if self.app_source is not None:
  207. app_globals = self._get_globals_from_signature(self.app_source)
  208. if isinstance(self.app_source, functools.partial):
  209. self.app_source = self.app_source.func
  210. # get the source from a function or module object
  211. source_code = "\n".join(
  212. [
  213. "\n".join(
  214. self.get_app_global_source(k, v) for k, v in app_globals.items()
  215. ),
  216. self._get_source_from_app_source(self.app_source),
  217. ]
  218. )
  219. with chdir(self.app_path):
  220. reflex.reflex._init(
  221. name=self.app_name,
  222. template=reflex.constants.Templates.DEFAULT,
  223. loglevel=reflex.constants.LogLevel.INFO,
  224. )
  225. self.app_module_path.write_text(source_code)
  226. else:
  227. # Just initialize the web folder.
  228. with chdir(self.app_path):
  229. reflex.utils.prerequisites.initialize_frontend_dependencies()
  230. with chdir(self.app_path):
  231. # ensure config and app are reloaded when testing different app
  232. reflex.config.get_config(reload=True)
  233. # Save decorated pages before importing the test app module
  234. before_decorated_pages = reflex.app.DECORATED_PAGES[self.app_name].copy()
  235. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  236. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  237. os.environ[reflex.constants.APP_HARNESS_FLAG] = "true"
  238. self.app_module = reflex.utils.prerequisites.get_compiled_app(
  239. # Do not reload the module for pre-existing apps (only apps generated from source)
  240. reload=self.app_source is not None
  241. )
  242. # Save the pages that were added during testing
  243. self._decorated_pages = [
  244. p
  245. for p in reflex.app.DECORATED_PAGES[self.app_name]
  246. if p not in before_decorated_pages
  247. ]
  248. self.app_instance = self.app_module.app
  249. if self.app_instance and isinstance(
  250. self.app_instance._state_manager, StateManagerRedis
  251. ):
  252. if self.app_instance._state is None:
  253. raise RuntimeError("State is not set.")
  254. # Create our own redis connection for testing.
  255. self.state_manager = StateManagerRedis.create(self.app_instance._state)
  256. else:
  257. self.state_manager = (
  258. self.app_instance._state_manager if self.app_instance else None
  259. )
  260. def _reload_state_module(self):
  261. """Reload the rx.State module to avoid conflict when reloading."""
  262. reload_state_module(module=f"{self.app_name}.{self.app_name}")
  263. def _get_backend_shutdown_handler(self):
  264. if self.backend is None:
  265. raise RuntimeError("Backend was not initialized.")
  266. original_shutdown = self.backend.shutdown
  267. async def _shutdown_redis(*args, **kwargs) -> None:
  268. # ensure redis is closed before event loop
  269. try:
  270. if self.app_instance is not None and isinstance(
  271. self.app_instance.state_manager, StateManagerRedis
  272. ):
  273. await self.app_instance.state_manager.close()
  274. except ValueError:
  275. pass
  276. await original_shutdown(*args, **kwargs)
  277. return _shutdown_redis
  278. def _start_backend(self, port: 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. # Cleanup decorated pages added during testing
  430. for page in self._decorated_pages:
  431. reflex.app.DECORATED_PAGES[self.app_name].remove(page)
  432. def __exit__(self, *excinfo) -> None:
  433. """Contextmanager protocol for `stop()`.
  434. Args:
  435. excinfo: sys.exc_info captured in the context block
  436. """
  437. self.stop()
  438. @staticmethod
  439. def _poll_for(
  440. target: Callable[[], T],
  441. timeout: TimeoutType = None,
  442. step: TimeoutType = None,
  443. ) -> T | bool:
  444. """Generic polling logic.
  445. Args:
  446. target: callable that returns truthy if polling condition is met.
  447. timeout: max polling time
  448. step: interval between checking target()
  449. Returns:
  450. return value of target() if truthy within timeout
  451. False if timeout elapses
  452. """
  453. if timeout is None:
  454. timeout = DEFAULT_TIMEOUT
  455. if step is None:
  456. step = POLL_INTERVAL
  457. deadline = time.time() + timeout
  458. while time.time() < deadline:
  459. success = target()
  460. if success:
  461. return success
  462. time.sleep(step)
  463. return False
  464. @staticmethod
  465. async def _poll_for_async(
  466. target: Callable[[], Coroutine[None, None, T]],
  467. timeout: TimeoutType = None,
  468. step: TimeoutType = None,
  469. ) -> T | bool:
  470. """Generic polling logic for async functions.
  471. Args:
  472. target: callable that returns truthy if polling condition is met.
  473. timeout: max polling time
  474. step: interval between checking target()
  475. Returns:
  476. return value of target() if truthy within timeout
  477. False if timeout elapses
  478. """
  479. if timeout is None:
  480. timeout = DEFAULT_TIMEOUT
  481. if step is None:
  482. step = POLL_INTERVAL
  483. deadline = time.time() + timeout
  484. while time.time() < deadline:
  485. success = await target()
  486. if success:
  487. return success
  488. await asyncio.sleep(step)
  489. return False
  490. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  491. """Poll backend server for listening sockets.
  492. Args:
  493. timeout: how long to wait for listening socket.
  494. Returns:
  495. first active listening socket on the backend
  496. Raises:
  497. RuntimeError: when the backend hasn't started running
  498. TimeoutError: when server or sockets are not ready
  499. """
  500. if self.backend is None:
  501. raise RuntimeError("Backend is not running.")
  502. backend = self.backend
  503. # check for servers to be initialized
  504. if not self._poll_for(
  505. target=lambda: getattr(backend, "servers", False),
  506. timeout=timeout,
  507. ):
  508. raise TimeoutError("Backend servers are not initialized.")
  509. # check for sockets to be listening
  510. if not self._poll_for(
  511. target=lambda: getattr(backend.servers[0], "sockets", False),
  512. timeout=timeout,
  513. ):
  514. raise TimeoutError("Backend is not listening.")
  515. return backend.servers[0].sockets[0]
  516. def frontend(
  517. self,
  518. driver_clz: type[WebDriver] | None = None,
  519. driver_kwargs: dict[str, Any] | None = None,
  520. driver_options: ArgOptions | None = None,
  521. driver_option_args: list[str] | None = None,
  522. driver_option_capabilities: dict[str, Any] | None = None,
  523. ) -> WebDriver:
  524. """Get a selenium webdriver instance pointed at the app.
  525. Args:
  526. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  527. webdriver.Edge, etc
  528. driver_kwargs: additional keyword arguments to pass to the webdriver constructor
  529. driver_options: selenium ArgOptions instance to pass to the webdriver constructor
  530. driver_option_args: additional arguments for the webdriver options
  531. driver_option_capabilities: additional capabilities for the webdriver options
  532. Returns:
  533. Instance of the given webdriver navigated to the frontend url of the app.
  534. Raises:
  535. RuntimeError: when selenium is not importable or frontend is not running
  536. """
  537. if not has_selenium:
  538. raise RuntimeError(
  539. "Frontend functionality requires `selenium` to be installed, "
  540. "and it could not be imported."
  541. )
  542. if self.frontend_url is None:
  543. raise RuntimeError("Frontend is not running.")
  544. want_headless = False
  545. if environment.APP_HARNESS_HEADLESS.get():
  546. want_headless = True
  547. if driver_clz is None:
  548. requested_driver = environment.APP_HARNESS_DRIVER.get()
  549. driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable]
  550. if driver_options is None:
  551. driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable]
  552. if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable]
  553. if driver_options is None:
  554. driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  555. driver_options.add_argument("--class=AppHarness")
  556. if want_headless:
  557. driver_options.add_argument("--headless=new")
  558. elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable]
  559. if driver_options is None:
  560. driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  561. if want_headless:
  562. driver_options.add_argument("-headless")
  563. elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable]
  564. if driver_options is None:
  565. driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  566. if want_headless:
  567. driver_options.add_argument("headless")
  568. if driver_options is None:
  569. raise RuntimeError(f"Could not determine options for {driver_clz}")
  570. if args := environment.APP_HARNESS_DRIVER_ARGS.get():
  571. for arg in args.split(","):
  572. driver_options.add_argument(arg)
  573. if driver_option_args is not None:
  574. for arg in driver_option_args:
  575. driver_options.add_argument(arg)
  576. if driver_option_capabilities is not None:
  577. for key, value in driver_option_capabilities.items():
  578. driver_options.set_capability(key, value)
  579. if driver_kwargs is None:
  580. driver_kwargs = {}
  581. driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType]
  582. driver.get(self.frontend_url)
  583. self._frontends.append(driver)
  584. return driver
  585. async def get_state(self, token: str) -> BaseState:
  586. """Get the state associated with the given token.
  587. Args:
  588. token: The state token to look up.
  589. Returns:
  590. The state instance associated with the given token
  591. Raises:
  592. RuntimeError: when the app hasn't started running
  593. """
  594. if self.state_manager is None:
  595. raise RuntimeError("state_manager is not set.")
  596. try:
  597. return await self.state_manager.get_state(token)
  598. finally:
  599. if isinstance(self.state_manager, StateManagerRedis):
  600. await self.state_manager.close()
  601. async def set_state(self, token: str, **kwargs) -> None:
  602. """Set the state associated with the given token.
  603. Args:
  604. token: The state token to set.
  605. kwargs: Attributes to set on the state.
  606. Raises:
  607. RuntimeError: when the app hasn't started running
  608. """
  609. if self.state_manager is None:
  610. raise RuntimeError("state_manager is not set.")
  611. state = await self.get_state(token)
  612. for key, value in kwargs.items():
  613. setattr(state, key, value)
  614. try:
  615. await self.state_manager.set_state(token, state)
  616. finally:
  617. if isinstance(self.state_manager, StateManagerRedis):
  618. await self.state_manager.close()
  619. @contextlib.asynccontextmanager
  620. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  621. """Modify the state associated with the given token and send update to frontend.
  622. Args:
  623. token: The state token to modify
  624. Yields:
  625. The state instance associated with the given token
  626. Raises:
  627. RuntimeError: when the app hasn't started running
  628. """
  629. if self.state_manager is None:
  630. raise RuntimeError("state_manager is not set.")
  631. if self.app_instance is None:
  632. raise RuntimeError("App is not running.")
  633. app_state_manager = self.app_instance.state_manager
  634. if isinstance(self.state_manager, StateManagerRedis):
  635. # Temporarily replace the app's state manager with our own, since
  636. # the redis connection is on the backend_thread event loop
  637. self.app_instance._state_manager = self.state_manager
  638. try:
  639. async with self.app_instance.modify_state(token) as state:
  640. yield state
  641. finally:
  642. if isinstance(self.state_manager, StateManagerRedis):
  643. self.app_instance._state_manager = app_state_manager
  644. await self.state_manager.close()
  645. def poll_for_content(
  646. self,
  647. element: WebElement,
  648. timeout: TimeoutType = None,
  649. exp_not_equal: str = "",
  650. ) -> str:
  651. """Poll element.text for change.
  652. Args:
  653. element: selenium webdriver element to check
  654. timeout: how long to poll element.text
  655. exp_not_equal: exit the polling loop when the element text does not match
  656. Returns:
  657. The element text when the polling loop exited
  658. Raises:
  659. TimeoutError: when the timeout expires before text changes
  660. """
  661. if not self._poll_for(
  662. target=lambda: element.text != exp_not_equal,
  663. timeout=timeout,
  664. ):
  665. raise TimeoutError(
  666. f"{element} content remains {exp_not_equal!r} while polling.",
  667. )
  668. return element.text
  669. def poll_for_value(
  670. self,
  671. element: WebElement,
  672. timeout: TimeoutType = None,
  673. exp_not_equal: str | Sequence[str] = "",
  674. ) -> str | None:
  675. """Poll element.get_attribute("value") for change.
  676. Args:
  677. element: selenium webdriver element to check
  678. timeout: how long to poll element value attribute
  679. exp_not_equal: exit the polling loop when the value does not match
  680. Returns:
  681. The element value when the polling loop exited
  682. Raises:
  683. TimeoutError: when the timeout expires before value changes
  684. """
  685. exp_not_equal = (
  686. (exp_not_equal,) if isinstance(exp_not_equal, str) else exp_not_equal
  687. )
  688. if not self._poll_for(
  689. target=lambda: element.get_attribute("value") not in exp_not_equal,
  690. timeout=timeout,
  691. ):
  692. raise TimeoutError(
  693. f"{element} content remains {exp_not_equal!r} while polling.",
  694. )
  695. return element.get_attribute("value")
  696. def poll_for_clients(self, timeout: TimeoutType = None) -> dict[str, BaseState]:
  697. """Poll app state_manager for any connected clients.
  698. Args:
  699. timeout: how long to wait for client states
  700. Returns:
  701. active state instances when the polling loop exited
  702. Raises:
  703. RuntimeError: when the app hasn't started running
  704. TimeoutError: when the timeout expires before any states are seen
  705. ValueError: when the state_manager is not a memory state manager
  706. """
  707. if self.app_instance is None:
  708. raise RuntimeError("App is not running.")
  709. state_manager = self.app_instance.state_manager
  710. if not isinstance(state_manager, (StateManagerMemory, StateManagerDisk)):
  711. raise ValueError("Only works with memory or disk state manager")
  712. if not self._poll_for(
  713. target=lambda: state_manager.states,
  714. timeout=timeout,
  715. ):
  716. raise TimeoutError("No states were observed while polling.")
  717. return state_manager.states
  718. class SimpleHTTPRequestHandlerCustomErrors(SimpleHTTPRequestHandler):
  719. """SimpleHTTPRequestHandler with custom error page handling."""
  720. def __init__(self, *args, error_page_map: dict[int, Path], **kwargs):
  721. """Initialize the handler.
  722. Args:
  723. error_page_map: map of error code to error page path
  724. *args: passed through to superclass
  725. **kwargs: passed through to superclass
  726. """
  727. self.error_page_map = error_page_map
  728. super().__init__(*args, **kwargs)
  729. def send_error(
  730. self, code: int, message: str | None = None, explain: str | None = None
  731. ) -> None:
  732. """Send the error page for the given error code.
  733. If the code matches a custom error page, then message and explain are
  734. ignored.
  735. Args:
  736. code: the error code
  737. message: the error message
  738. explain: the error explanation
  739. """
  740. error_page = self.error_page_map.get(code)
  741. if error_page:
  742. self.send_response(code, message)
  743. self.send_header("Connection", "close")
  744. body = error_page.read_bytes()
  745. self.send_header("Content-Type", self.error_content_type)
  746. self.send_header("Content-Length", str(len(body)))
  747. self.end_headers()
  748. self.wfile.write(body)
  749. else:
  750. super().send_error(code, message, explain)
  751. class Subdir404TCPServer(socketserver.TCPServer):
  752. """TCPServer for SimpleHTTPRequestHandlerCustomErrors that serves from a subdir."""
  753. def __init__(
  754. self,
  755. *args,
  756. root: Path,
  757. error_page_map: dict[int, Path] | None,
  758. **kwargs,
  759. ):
  760. """Initialize the server.
  761. Args:
  762. root: the root directory to serve from
  763. error_page_map: map of error code to error page path
  764. *args: passed through to superclass
  765. **kwargs: passed through to superclass
  766. """
  767. self.root = root
  768. self.error_page_map = error_page_map or {}
  769. super().__init__(*args, **kwargs)
  770. def finish_request(self, request: socket.socket, client_address: tuple[str, int]):
  771. """Finish one request by instantiating RequestHandlerClass.
  772. Args:
  773. request: the requesting socket
  774. client_address: (host, port) referring to the client's address.
  775. """
  776. self.RequestHandlerClass(
  777. request,
  778. client_address,
  779. self,
  780. directory=str(self.root), # pyright: ignore [reportCallIssue]
  781. error_page_map=self.error_page_map, # pyright: ignore [reportCallIssue]
  782. )
  783. class AppHarnessProd(AppHarness):
  784. """AppHarnessProd executes a reflex app in-process for testing.
  785. In prod mode, instead of running `next dev` the app is exported as static
  786. files and served via the builtin python http.server with custom 404 redirect
  787. handling. Additionally, the backend runs in multi-worker mode.
  788. """
  789. frontend_thread: threading.Thread | None = None
  790. frontend_server: Subdir404TCPServer | None = None
  791. def _run_frontend(self):
  792. web_root = (
  793. self.app_path
  794. / reflex.utils.prerequisites.get_web_dir()
  795. / reflex.constants.Dirs.STATIC
  796. )
  797. error_page_map = {
  798. 404: web_root / "404.html",
  799. }
  800. with Subdir404TCPServer(
  801. ("", 0),
  802. SimpleHTTPRequestHandlerCustomErrors,
  803. root=web_root,
  804. error_page_map=error_page_map,
  805. ) as self.frontend_server:
  806. self.frontend_url = "http://localhost:{1}".format(
  807. *self.frontend_server.socket.getsockname()
  808. )
  809. self.frontend_server.serve_forever()
  810. def _start_frontend(self):
  811. # Set up the frontend.
  812. with chdir(self.app_path):
  813. config = reflex.config.get_config()
  814. config.api_url = "http://{}:{}".format(
  815. *self._poll_for_servers().getsockname(),
  816. )
  817. reflex.reflex.export(
  818. zipping=False,
  819. frontend=True,
  820. backend=False,
  821. loglevel=reflex.constants.LogLevel.INFO,
  822. env=reflex.constants.Env.PROD,
  823. )
  824. self.frontend_thread = threading.Thread(target=self._run_frontend)
  825. self.frontend_thread.start()
  826. def _wait_frontend(self):
  827. self._poll_for(lambda: self.frontend_server is not None)
  828. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  829. raise RuntimeError("Frontend did not start")
  830. def _start_backend(self):
  831. if self.app_instance is None:
  832. raise RuntimeError("App was not initialized.")
  833. environment.REFLEX_SKIP_COMPILE.set(True)
  834. self.backend = uvicorn.Server(
  835. uvicorn.Config(
  836. app=self.app_instance,
  837. host="127.0.0.1",
  838. port=0,
  839. workers=reflex.utils.processes.get_num_workers(),
  840. ),
  841. )
  842. self.backend.shutdown = self._get_backend_shutdown_handler()
  843. self.backend_thread = threading.Thread(target=self.backend.run)
  844. self.backend_thread.start()
  845. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  846. try:
  847. return super()._poll_for_servers(timeout)
  848. finally:
  849. environment.REFLEX_SKIP_COMPILE.set(None)
  850. def stop(self):
  851. """Stop the frontend python webserver."""
  852. super().stop()
  853. if self.frontend_server is not None:
  854. self.frontend_server.shutdown()
  855. if self.frontend_thread is not None:
  856. self.frontend_thread.join()