1
0

testing.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987
  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. try:
  45. from selenium import webdriver
  46. from selenium.webdriver.remote.webdriver import WebDriver
  47. if TYPE_CHECKING:
  48. from selenium.webdriver.common.options import ArgOptions
  49. from selenium.webdriver.remote.webelement import WebElement
  50. has_selenium = True
  51. except ImportError:
  52. has_selenium = False
  53. # The timeout (minutes) to check for the port.
  54. DEFAULT_TIMEOUT = 15
  55. POLL_INTERVAL = 0.25
  56. FRONTEND_POPEN_ARGS = {}
  57. T = TypeVar("T")
  58. TimeoutType = int | float | None
  59. if platform.system() == "Windows":
  60. FRONTEND_POPEN_ARGS["creationflags"] = subprocess.CREATE_NEW_PROCESS_GROUP # pyright: ignore [reportAttributeAccessIssue]
  61. FRONTEND_POPEN_ARGS["shell"] = True
  62. else:
  63. FRONTEND_POPEN_ARGS["start_new_session"] = True
  64. # borrowed from py3.11
  65. class chdir(contextlib.AbstractContextManager): # noqa: N801
  66. """Non thread-safe context manager to change the current working directory."""
  67. def __init__(self, path: str | Path):
  68. """Prepare contextmanager.
  69. Args:
  70. path: the path to change to
  71. """
  72. self.path = path
  73. self._old_cwd = []
  74. def __enter__(self):
  75. """Save current directory and perform chdir."""
  76. self._old_cwd.append(Path.cwd())
  77. os.chdir(self.path)
  78. def __exit__(self, *excinfo):
  79. """Change back to previous directory on stack.
  80. Args:
  81. excinfo: sys.exc_info captured in the context block
  82. """
  83. os.chdir(self._old_cwd.pop())
  84. @dataclasses.dataclass
  85. class AppHarness:
  86. """AppHarness executes a reflex app in-process for testing."""
  87. app_name: str
  88. app_source: (
  89. Callable[[], None] | types.ModuleType | str | functools.partial[Any] | None
  90. )
  91. app_path: Path
  92. app_module_path: Path
  93. app_module: types.ModuleType | None = None
  94. app_instance: reflex.App | None = None
  95. frontend_process: subprocess.Popen | None = None
  96. frontend_url: str | None = None
  97. frontend_output_thread: threading.Thread | None = None
  98. backend_thread: threading.Thread | None = None
  99. backend: uvicorn.Server | None = None
  100. state_manager: StateManager | None = None
  101. _frontends: list[WebDriver] = 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. get_config().loglevel = reflex.constants.LogLevel.INFO
  220. with chdir(self.app_path):
  221. reflex.reflex._init(
  222. name=self.app_name,
  223. template=reflex.constants.Templates.DEFAULT,
  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. # Ensure the AppHarness test does not skip State assignment due to running via pytest
  234. os.environ.pop(reflex.constants.PYTEST_CURRENT_TEST, None)
  235. os.environ[reflex.constants.APP_HARNESS_FLAG] = "true"
  236. self.app_module = reflex.utils.prerequisites.get_compiled_app(
  237. # Do not reload the module for pre-existing apps (only apps generated from source)
  238. reload=self.app_source is not None
  239. )
  240. self.app_instance = self.app_module.app
  241. if self.app_instance and isinstance(
  242. self.app_instance._state_manager, StateManagerRedis
  243. ):
  244. if self.app_instance._state is None:
  245. raise RuntimeError("State is not set.")
  246. # Create our own redis connection for testing.
  247. self.state_manager = StateManagerRedis.create(self.app_instance._state)
  248. else:
  249. self.state_manager = (
  250. self.app_instance._state_manager if self.app_instance else None
  251. )
  252. def _reload_state_module(self):
  253. """Reload the rx.State module to avoid conflict when reloading."""
  254. reload_state_module(module=f"{self.app_name}.{self.app_name}")
  255. def _get_backend_shutdown_handler(self):
  256. if self.backend is None:
  257. raise RuntimeError("Backend was not initialized.")
  258. original_shutdown = self.backend.shutdown
  259. async def _shutdown(*args, **kwargs) -> None:
  260. # ensure redis is closed before event loop
  261. if self.app_instance is not None and isinstance(
  262. self.app_instance.state_manager, StateManagerRedis
  263. ):
  264. with contextlib.suppress(ValueError):
  265. await self.app_instance.state_manager.close()
  266. # socketio shutdown handler
  267. if self.app_instance is not None and self.app_instance.sio is not None:
  268. with contextlib.suppress(TypeError):
  269. await self.app_instance.sio.shutdown()
  270. # sqlalchemy async engine shutdown handler
  271. try:
  272. async_engine = reflex.model.get_async_engine(None)
  273. except ValueError:
  274. pass
  275. else:
  276. await async_engine.dispose()
  277. await original_shutdown(*args, **kwargs)
  278. return _shutdown
  279. def _start_backend(self, port: int = 0):
  280. if self.app_instance is None or self.app_instance._api is None:
  281. raise RuntimeError("App was not initialized.")
  282. self.backend = uvicorn.Server(
  283. uvicorn.Config(
  284. app=self.app_instance._api,
  285. host="127.0.0.1",
  286. port=port,
  287. )
  288. )
  289. self.backend.shutdown = self._get_backend_shutdown_handler()
  290. with chdir(self.app_path):
  291. self.backend_thread = threading.Thread(target=self.backend.run)
  292. self.backend_thread.start()
  293. async def _reset_backend_state_manager(self):
  294. """Reset the StateManagerRedis event loop affinity.
  295. This is necessary when the backend is restarted and the state manager is a
  296. StateManagerRedis instance.
  297. Raises:
  298. RuntimeError: when the state manager cannot be reset
  299. """
  300. if (
  301. self.app_instance is not None
  302. and isinstance(
  303. self.app_instance.state_manager,
  304. StateManagerRedis,
  305. )
  306. and self.app_instance._state is not None
  307. ):
  308. with contextlib.suppress(RuntimeError):
  309. await self.app_instance.state_manager.close()
  310. self.app_instance._state_manager = StateManagerRedis.create(
  311. state=self.app_instance._state,
  312. )
  313. if not isinstance(self.app_instance.state_manager, StateManagerRedis):
  314. raise RuntimeError("Failed to reset state manager.")
  315. def _start_frontend(self):
  316. # Set up the frontend.
  317. with chdir(self.app_path):
  318. config = reflex.config.get_config()
  319. config.api_url = "http://{}:{}".format(
  320. *self._poll_for_servers().getsockname(),
  321. )
  322. reflex.utils.build.setup_frontend(self.app_path)
  323. # Start the frontend.
  324. self.frontend_process = reflex.utils.processes.new_process(
  325. [
  326. *reflex.utils.prerequisites.get_js_package_executor(raise_on_none=True)[
  327. 0
  328. ],
  329. "run",
  330. "dev",
  331. ],
  332. cwd=self.app_path / reflex.utils.prerequisites.get_web_dir(),
  333. env={"PORT": "0"},
  334. **FRONTEND_POPEN_ARGS,
  335. )
  336. def _wait_frontend(self):
  337. while self.frontend_url is None:
  338. line = (
  339. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  340. )
  341. if not line:
  342. break
  343. print(line) # for pytest diagnosis #noqa: T201
  344. m = re.search(reflex.constants.Next.FRONTEND_LISTENING_REGEX, line)
  345. if m is not None:
  346. self.frontend_url = m.group(1)
  347. config = reflex.config.get_config()
  348. config.deploy_url = self.frontend_url
  349. break
  350. if self.frontend_url is None:
  351. raise RuntimeError("Frontend did not start")
  352. def consume_frontend_output():
  353. while True:
  354. try:
  355. line = (
  356. self.frontend_process.stdout.readline() # pyright: ignore [reportOptionalMemberAccess]
  357. )
  358. # catch I/O operation on closed file.
  359. except ValueError as e:
  360. console.error(str(e))
  361. break
  362. if not line:
  363. break
  364. self.frontend_output_thread = threading.Thread(target=consume_frontend_output)
  365. self.frontend_output_thread.start()
  366. def start(self) -> AppHarness:
  367. """Start the backend in a new thread and dev frontend as a separate process.
  368. Returns:
  369. self
  370. """
  371. self._initialize_app()
  372. self._start_backend()
  373. self._start_frontend()
  374. self._wait_frontend()
  375. return self
  376. @staticmethod
  377. def get_app_global_source(key: str, value: Any):
  378. """Get the source code of a global object.
  379. If value is a function or class we render the actual
  380. source of value otherwise we assign value to key.
  381. Args:
  382. key: variable name to assign value to.
  383. value: value of the global variable.
  384. Returns:
  385. The rendered app global code.
  386. """
  387. if not inspect.isclass(value) and not inspect.isfunction(value):
  388. return f"{key} = {value!r}"
  389. return inspect.getsource(value)
  390. def __enter__(self) -> AppHarness:
  391. """Contextmanager protocol for `start()`.
  392. Returns:
  393. Instance of AppHarness after calling start()
  394. """
  395. return self.start()
  396. def stop(self) -> None:
  397. """Stop the frontend and backend servers."""
  398. # Quit browsers first to avoid any lingering events being sent during shutdown.
  399. for driver in self._frontends:
  400. driver.quit()
  401. self._reload_state_module()
  402. if self.backend is not None:
  403. self.backend.should_exit = True
  404. if self.frontend_process is not None:
  405. # https://stackoverflow.com/a/70565806
  406. frontend_children = psutil.Process(self.frontend_process.pid).children(
  407. recursive=True,
  408. )
  409. if platform.system() == "Windows":
  410. self.frontend_process.terminate()
  411. else:
  412. pgrp = os.getpgid(self.frontend_process.pid)
  413. os.killpg(pgrp, signal.SIGTERM)
  414. # kill any remaining child processes
  415. for child in frontend_children:
  416. # It's okay if the process is already gone.
  417. with contextlib.suppress(psutil.NoSuchProcess):
  418. child.terminate()
  419. _, still_alive = psutil.wait_procs(frontend_children, timeout=3)
  420. for child in still_alive:
  421. # It's okay if the process is already gone.
  422. with contextlib.suppress(psutil.NoSuchProcess):
  423. child.kill()
  424. # wait for main process to exit
  425. self.frontend_process.communicate()
  426. if self.backend_thread is not None:
  427. self.backend_thread.join()
  428. if self.frontend_output_thread is not None:
  429. self.frontend_output_thread.join()
  430. def __exit__(self, *excinfo) -> None:
  431. """Contextmanager protocol for `stop()`.
  432. Args:
  433. excinfo: sys.exc_info captured in the context block
  434. """
  435. self.stop()
  436. @staticmethod
  437. def _poll_for(
  438. target: Callable[[], T],
  439. timeout: TimeoutType = None,
  440. step: TimeoutType = None,
  441. ) -> T | bool:
  442. """Generic polling logic.
  443. Args:
  444. target: callable that returns truthy if polling condition is met.
  445. timeout: max polling time
  446. step: interval between checking target()
  447. Returns:
  448. return value of target() if truthy within timeout
  449. False if timeout elapses
  450. """
  451. if timeout is None:
  452. timeout = DEFAULT_TIMEOUT
  453. if step is None:
  454. step = POLL_INTERVAL
  455. deadline = time.time() + timeout
  456. while time.time() < deadline:
  457. success = target()
  458. if success:
  459. return success
  460. time.sleep(step)
  461. return False
  462. @staticmethod
  463. async def _poll_for_async(
  464. target: Callable[[], Coroutine[None, None, T]],
  465. timeout: TimeoutType = None,
  466. step: TimeoutType = None,
  467. ) -> T | bool:
  468. """Generic polling logic for async functions.
  469. Args:
  470. target: callable that returns truthy if polling condition is met.
  471. timeout: max polling time
  472. step: interval between checking target()
  473. Returns:
  474. return value of target() if truthy within timeout
  475. False if timeout elapses
  476. """
  477. if timeout is None:
  478. timeout = DEFAULT_TIMEOUT
  479. if step is None:
  480. step = POLL_INTERVAL
  481. deadline = time.time() + timeout
  482. while time.time() < deadline:
  483. success = await target()
  484. if success:
  485. return success
  486. await asyncio.sleep(step)
  487. return False
  488. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  489. """Poll backend server for listening sockets.
  490. Args:
  491. timeout: how long to wait for listening socket.
  492. Returns:
  493. first active listening socket on the backend
  494. Raises:
  495. RuntimeError: when the backend hasn't started running
  496. TimeoutError: when server or sockets are not ready
  497. """
  498. if self.backend is None:
  499. raise RuntimeError("Backend is not running.")
  500. backend = self.backend
  501. # check for servers to be initialized
  502. if not self._poll_for(
  503. target=lambda: getattr(backend, "servers", False),
  504. timeout=timeout,
  505. ):
  506. raise TimeoutError("Backend servers are not initialized.")
  507. # check for sockets to be listening
  508. if not self._poll_for(
  509. target=lambda: getattr(backend.servers[0], "sockets", False),
  510. timeout=timeout,
  511. ):
  512. raise TimeoutError("Backend is not listening.")
  513. return backend.servers[0].sockets[0]
  514. def frontend(
  515. self,
  516. driver_clz: type[WebDriver] | None = None,
  517. driver_kwargs: dict[str, Any] | None = None,
  518. driver_options: ArgOptions | None = None,
  519. driver_option_args: list[str] | None = None,
  520. driver_option_capabilities: dict[str, Any] | None = None,
  521. ) -> WebDriver:
  522. """Get a selenium webdriver instance pointed at the app.
  523. Args:
  524. driver_clz: webdriver.Chrome (default), webdriver.Firefox, webdriver.Safari,
  525. webdriver.Edge, etc
  526. driver_kwargs: additional keyword arguments to pass to the webdriver constructor
  527. driver_options: selenium ArgOptions instance to pass to the webdriver constructor
  528. driver_option_args: additional arguments for the webdriver options
  529. driver_option_capabilities: additional capabilities for the webdriver options
  530. Returns:
  531. Instance of the given webdriver navigated to the frontend url of the app.
  532. Raises:
  533. RuntimeError: when selenium is not importable or frontend is not running
  534. """
  535. if not has_selenium:
  536. raise RuntimeError(
  537. "Frontend functionality requires `selenium` to be installed, "
  538. "and it could not be imported."
  539. )
  540. if self.frontend_url is None:
  541. raise RuntimeError("Frontend is not running.")
  542. want_headless = False
  543. if environment.APP_HARNESS_HEADLESS.get():
  544. want_headless = True
  545. if driver_clz is None:
  546. requested_driver = environment.APP_HARNESS_DRIVER.get()
  547. driver_clz = getattr(webdriver, requested_driver) # pyright: ignore [reportPossiblyUnboundVariable]
  548. if driver_options is None:
  549. driver_options = getattr(webdriver, f"{requested_driver}Options")() # pyright: ignore [reportPossiblyUnboundVariable]
  550. if driver_clz is webdriver.Chrome: # pyright: ignore [reportPossiblyUnboundVariable]
  551. if driver_options is None:
  552. driver_options = webdriver.ChromeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  553. driver_options.add_argument("--class=AppHarness")
  554. if want_headless:
  555. driver_options.add_argument("--headless=new")
  556. elif driver_clz is webdriver.Firefox: # pyright: ignore [reportPossiblyUnboundVariable]
  557. if driver_options is None:
  558. driver_options = webdriver.FirefoxOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  559. if want_headless:
  560. driver_options.add_argument("-headless")
  561. elif driver_clz is webdriver.Edge: # pyright: ignore [reportPossiblyUnboundVariable]
  562. if driver_options is None:
  563. driver_options = webdriver.EdgeOptions() # pyright: ignore [reportPossiblyUnboundVariable]
  564. if want_headless:
  565. driver_options.add_argument("headless")
  566. if driver_options is None:
  567. raise RuntimeError(f"Could not determine options for {driver_clz}")
  568. if args := environment.APP_HARNESS_DRIVER_ARGS.get():
  569. for arg in args.split(","):
  570. driver_options.add_argument(arg)
  571. if driver_option_args is not None:
  572. for arg in driver_option_args:
  573. driver_options.add_argument(arg)
  574. if driver_option_capabilities is not None:
  575. for key, value in driver_option_capabilities.items():
  576. driver_options.set_capability(key, value)
  577. if driver_kwargs is None:
  578. driver_kwargs = {}
  579. driver = driver_clz(options=driver_options, **driver_kwargs) # pyright: ignore [reportOptionalCall, reportArgumentType]
  580. driver.get(self.frontend_url)
  581. self._frontends.append(driver)
  582. return driver
  583. async def get_state(self, token: str) -> BaseState:
  584. """Get the state associated with the given token.
  585. Args:
  586. token: The state token to look up.
  587. Returns:
  588. The state instance associated with the given token
  589. Raises:
  590. RuntimeError: when the app hasn't started running
  591. """
  592. if self.state_manager is None:
  593. raise RuntimeError("state_manager is not set.")
  594. try:
  595. return await self.state_manager.get_state(token)
  596. finally:
  597. if isinstance(self.state_manager, StateManagerRedis):
  598. await self.state_manager.close()
  599. async def set_state(self, token: str, **kwargs) -> None:
  600. """Set the state associated with the given token.
  601. Args:
  602. token: The state token to set.
  603. kwargs: Attributes to set on the state.
  604. Raises:
  605. RuntimeError: when the app hasn't started running
  606. """
  607. if self.state_manager is None:
  608. raise RuntimeError("state_manager is not set.")
  609. state = await self.get_state(token)
  610. for key, value in kwargs.items():
  611. setattr(state, key, value)
  612. try:
  613. await self.state_manager.set_state(token, state)
  614. finally:
  615. if isinstance(self.state_manager, StateManagerRedis):
  616. await self.state_manager.close()
  617. @contextlib.asynccontextmanager
  618. async def modify_state(self, token: str) -> AsyncIterator[BaseState]:
  619. """Modify the state associated with the given token and send update to frontend.
  620. Args:
  621. token: The state token to modify
  622. Yields:
  623. The state instance associated with the given token
  624. Raises:
  625. RuntimeError: when the app hasn't started running
  626. """
  627. if self.state_manager is None:
  628. raise RuntimeError("state_manager is not set.")
  629. if self.app_instance is None:
  630. raise RuntimeError("App is not running.")
  631. app_state_manager = self.app_instance.state_manager
  632. if isinstance(self.state_manager, StateManagerRedis):
  633. # Temporarily replace the app's state manager with our own, since
  634. # the redis connection is on the backend_thread event loop
  635. self.app_instance._state_manager = self.state_manager
  636. try:
  637. async with self.app_instance.modify_state(token) as state:
  638. yield state
  639. finally:
  640. if isinstance(self.state_manager, StateManagerRedis):
  641. self.app_instance._state_manager = app_state_manager
  642. await self.state_manager.close()
  643. def poll_for_content(
  644. self,
  645. element: WebElement,
  646. timeout: TimeoutType = None,
  647. exp_not_equal: str = "",
  648. ) -> str:
  649. """Poll element.text for change.
  650. Args:
  651. element: selenium webdriver element to check
  652. timeout: how long to poll element.text
  653. exp_not_equal: exit the polling loop when the element text does not match
  654. Returns:
  655. The element text when the polling loop exited
  656. Raises:
  657. TimeoutError: when the timeout expires before text changes
  658. """
  659. if not self._poll_for(
  660. target=lambda: element.text != exp_not_equal,
  661. timeout=timeout,
  662. ):
  663. raise TimeoutError(
  664. f"{element} content remains {exp_not_equal!r} while polling.",
  665. )
  666. return element.text
  667. def poll_for_value(
  668. self,
  669. element: WebElement,
  670. timeout: TimeoutType = None,
  671. exp_not_equal: str | Sequence[str] = "",
  672. ) -> str | None:
  673. """Poll element.get_attribute("value") for change.
  674. Args:
  675. element: selenium webdriver element to check
  676. timeout: how long to poll element value attribute
  677. exp_not_equal: exit the polling loop when the value does not match
  678. Returns:
  679. The element value when the polling loop exited
  680. Raises:
  681. TimeoutError: when the timeout expires before value changes
  682. """
  683. exp_not_equal = (
  684. (exp_not_equal,) if isinstance(exp_not_equal, str) else exp_not_equal
  685. )
  686. if not self._poll_for(
  687. target=lambda: element.get_attribute("value") not in 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: threading.Thread | None = None
  788. frontend_server: Subdir404TCPServer | None = 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://{}:{}".format(
  813. *self._poll_for_servers().getsockname(),
  814. )
  815. get_config().loglevel = reflex.constants.LogLevel.INFO
  816. if reflex.utils.prerequisites.needs_reinit(frontend=True):
  817. reflex.reflex._init(name=get_config().app_name)
  818. export(
  819. zipping=False,
  820. frontend=True,
  821. backend=False,
  822. loglevel=reflex.constants.LogLevel.INFO,
  823. env=reflex.constants.Env.PROD,
  824. )
  825. self.frontend_thread = threading.Thread(target=self._run_frontend)
  826. self.frontend_thread.start()
  827. def _wait_frontend(self):
  828. self._poll_for(lambda: self.frontend_server is not None)
  829. if self.frontend_server is None or not self.frontend_server.socket.fileno():
  830. raise RuntimeError("Frontend did not start")
  831. def _start_backend(self):
  832. if self.app_instance is None:
  833. raise RuntimeError("App was not initialized.")
  834. environment.REFLEX_SKIP_COMPILE.set(True)
  835. self.backend = uvicorn.Server(
  836. uvicorn.Config(
  837. app=self.app_instance,
  838. host="127.0.0.1",
  839. port=0,
  840. workers=reflex.utils.processes.get_num_workers(),
  841. ),
  842. )
  843. self.backend.shutdown = self._get_backend_shutdown_handler()
  844. self.backend_thread = threading.Thread(target=self.backend.run)
  845. self.backend_thread.start()
  846. def _poll_for_servers(self, timeout: TimeoutType = None) -> socket.socket:
  847. try:
  848. return super()._poll_for_servers(timeout)
  849. finally:
  850. environment.REFLEX_SKIP_COMPILE.set(None)
  851. def stop(self):
  852. """Stop the frontend python webserver."""
  853. super().stop()
  854. if self.frontend_server is not None:
  855. self.frontend_server.shutdown()
  856. if self.frontend_thread is not None:
  857. self.frontend_thread.join()