testing.py 35 KB

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