testing.py 35 KB

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