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